|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 kaobiel 于 2022-9-13 19:57 编辑
用while循环遍历列表找出里面的偶数,然后在把偶数组成新的列表。
exl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = 0
while x < exl:
if exl % 2 == 0:
print(f"列表中的偶数:{exl}")
x += 1
---------------------------------------
while x < exl:这里报错TypeError: '<' not supported between instances of 'int' and 'list'
我改成int(exl)也不行这里怎么改,在把偶数组成一个新的列表代码要怎么写
你想用 while 循环,可以这样改代码:
- exl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- x = 0
- new_exl = []
- while x < len(exl):
- if exl[x] % 2 == 0:
- new_exl.append(exl[x])
- x += 1
- print(new_exl)
复制代码
可以用过滤器过滤出偶数,参考代码:
- exl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- result = filter(lambda x : not x % 2, exl)
- print(list(result))
复制代码
|
|