gpt4 book ai didi

python - 仅打印嵌套列表中的偶数

转载 作者:行者123 更新时间:2023-12-01 00:49:06 25 4
gpt4 key购买 nike

这就是我所拥有的:

mylist1 = [[1,2,3], [4,5,6], [7,8,9]]   

for i in mylist1:
if i[0] % 2 == 0:
print(i[0])
if i[1] % 2 == 0:
print(i[1])
if i[2] % 2 == 0:
print(i[2])

有没有更短的方法?

最佳答案

列表理解?

print('\n'.join(str(i) for sublist in mylist1 for i in sublist if i % 2 == 0))

更少的核心列表理解?

for sublist in mylist1:
print('\n'.join(i for i in sublist if i % 2 == 0))

for循环?

for sublist in mylist1:
for i in sublist:
if i % 2 == 0:
print(i)

关于python - 仅打印嵌套列表中的偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com