如何打印具有特定质量的列表?

时间:2015-03-22 08:06:02

标签: python list elements

假设我们有4个列表:

["LA","California"]
["NV","Nevada"]
["NY","New York"]
["SF","California"]

如何编写仅打印出第1和第4个列表的代码,因为它们都有"California"作为第2个元素?

4 个答案:

答案 0 :(得分:1)

假设您有一个列表列表:

list_of_lists = [["LA","California"],
                 ["NV","Nevada"],
                 ["NY","New York"],
                 ["SF","California"]]

然后,您只能打印出最后位置"California"的列表:

for L in list_of_lists:
    if L[-1] == "California":
        print(L)

答案 1 :(得分:1)

L = [["LA","California"]
["NV","Nevada"],
["NY","New York"],
["SF","California"]]
for list1 in L:
    if list1[1] == "California":
        print list1

答案 2 :(得分:1)

好像你有列表清单

>>> l = [["LA","California"],
["NV","Nevada"],
["NY","New York"],
["SF","California"]]
>>> [i for i in l if i[1] == 'California']
[['LA', 'California'], ['SF', 'California']]

答案 3 :(得分:1)

您可以查看filter功能

>>> l = [["LA","California"],
... ["NV","Nevada"],
... ["NY","New York"],
... ["SF","California"]]
>>> list(filter(lambda x:x[1]=="California",l))
[['LA', 'California'], ['SF', 'California']]