如何在python中的嵌套列表中访问元组中的特定项

时间:2016-05-20 18:27:20

标签: python

我有一个如下所示的列表。

List = [[('1', 'AR123 <br/> ')], [('8', 'AR987 <br/> SR149728 <br/> Fix for BOM')], []]

需要输出:

AR123
AR987
SR149728
Fix for BOM
你能帮我解决这个问题吗? 提前谢谢。

3 个答案:

答案 0 :(得分:1)

print list[0][1], list[1][1]

如果我正确读取了这个,你想要每个子列表的第二个元素。更通用的版本是

for item in list:
    print item[1],

print

答案 1 :(得分:0)

试试这个,

List = [[('1', 'AR123 <br/> ')], [('8', 'AR987 <br/> SR149728 <br/> Fix for BOM')], []]


str_list = [t[1].split('<br/>') for sublist in List for t in sublist]
# [['AR123 ', ' '], ['AR987 ', ' SR149728 ', ' Fix for BOM']]

result = [s.strip() for sublist in str_list for s in sublist if s.strip()]
# ['AR123', 'AR987', 'SR149728', 'Fix for BOM']

print('\n'.join(result))
# Output
AR123
AR987
SR149728
Fix for BOM

以前的回答,

lists = [[('1', 'AR123 ')], [('8', 'AR987 SR149728 Fix for BOM')], []]

result = [t[1] for sublist in lists for t in sublist]

print(result)
# Output
['AR123 ', 'AR987 SR149728 Fix for BOM']

答案 2 :(得分:0)

元组嵌套在单项列表

List = [[('1', 'AR123 ')], [('8', 'AR987 SR149728 Fix for BOM')], []]

print(List[1][0][1])

没有额外的列表项

List = [('1', 'AR123 '), ('8', 'AR987 SR149728 Fix for BOM'), None]

print(List[1][1])

两者都返回:

AR987 SR149728修复BOM