如何访问python中列表中元组内的列表

时间:2017-05-17 14:57:47

标签: python python-2.7

我是python的新手。试图学习如何访问列表中元组内的列表。我的名单是:

holidays = [(0,),
 (1, [2, 16]),
 (2, [20]),
 (4, [14]),
 (5, [29]),
 (7, [4]),
 (9, [4]),
 (11, [23, 24]),
 (12, [25])]

我想知道以更有效的方式访问每个元组及其列表的最佳方法。我尝试使用:

for i, tuples in enumerate(holidays):
    for list in tuples:
        print list

但我收到以下错误:

for list in tuples:
TypeError: 'int' object is not iterable

非常感谢帮助。

4 个答案:

答案 0 :(得分:1)

您需要删除第一个for循环中的i:

for tuples in enumerate(holidays):
    for list in tuples:
        print list

答案 1 :(得分:1)

简短版

[y for x in holidays if isinstance(x, tuple) for y in x if isinstance(y, list)]

你不能在一个整数的LOOP中做一个for ..这就是程序崩溃的原因

答案 2 :(得分:0)

将你的第一个元素0改为(0),同样,从你的for循环中删除'i',正如Stavros所说,它会起作用。

IndexRedirect

枚举中的元组(假期):     元组中的列表:         打印列表

答案 3 :(得分:0)

好吧,你的假期列表并不统一:第一个条目是整数(0),其他条目是元组。

List<Integer> nonRatedPubs = new ArrayList<>();
nonRatedPubs.addAll(allBooksIDs);

这是一个可能的循环:

holidays = [0,  # <- integer
    (1, [2, 16]),
    (2, [20]),
    (4, [14]),
    (5, [29]),
    (7, [4]),
    (9, [4]),
    (11, [23, 24]),
    (12, [25])]

我们使用unpaking来提取。 请参阅Python教程中的Tuples and Sequences