仅打印嵌套列表中的偶数

时间:2019-06-22 01:30:33

标签: python list for-loop

这就是我所拥有的:

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])

有更短的方法吗?

6 个答案:

答案 0 :(得分:1)

列表理解?

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 sublist in mylist1:
    for i in sublist:
        if i % 2 == 0:
            print(i)

答案 1 :(得分:1)

您可以将过滤器与itertools的chain.from_iterable结合使用:

from itertools import chain
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]   

print(list(filter(lambda x: x % 2 == 0, chain.from_iterable(mylist1))))

# [2, 4, 6, 8]

答案 2 :(得分:0)

您可以使用嵌套循环尝试此操作。

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

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

答案 3 :(得分:0)

如果您知道格式将是列表列表,那么我想您可以只使用嵌套的循环

kd -kl

除非您要求它在CPU时间方面更快,否则我可能会使用numpy。继续尝试吧!

答案 4 :(得分:0)

您只需将data = np.genfromtxt("ca1_data/ridership.csv", delimiter=',',skip_header=1, dtype=[('Year','i4'),('Mode','U50'),('Ridership','U50')], missing_values=['na','-'],filling_values=[0]) mrt = data[data['Mode']=='MRT']['Ridership'] bus = data[data['Mode']=='Bus']['Ridership'] labels = np.arange(1995,2017) fig = plt.figure(figsize=(15,10)) ax1 = fig.add_subplot(111) ax1.scatter(labels, bus, c='b', label='Bus Ridership') ax1.scatter(labels, mrt,c='r', label='MRT Ridership') plt.title(title) plt.xlabel('Years') plt.ylabel('Average Daily Ridership') plt.legend(loc='upper left'); plt.show() 传递到*param即可:

chain

答案 5 :(得分:0)

还有另一种选择,一种不使用进口的单线:

print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)])

或者将它们放在单独的行上很重要:

print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)], sep = "\n")