【发布时间】:2020-04-20 18:53:19
【问题描述】:
我的函数desired_headers() 从“结果”对象中删除元组,其中元组中的第一个元素与标题列表中的任何字符串都不匹配。来自 result1 对象的 ['Fish', 'Dolphin'] 和 ['Local Auth', 'bucket'] 已从 result3 中删除。
然后它打印索引号和元组列表,如下面的当前输出所示。
我的目标是使用我当前的输出将元组列表“重新打包”在一起并存储在一个对象中。
headers2 = ['Group', 'Owner', 'Person in charge', 'Type of Service',
'Registered Care Categories*', 'Specialist Care Categories',
'Languages Spoken by Staff (other than English)','Single Rooms',
'Shared Rooms','Facilities & Service']
result1 = [['Group', 'MacIntyre'], ['Person in charge', ' Vivienne Donald (Manager)'],
['Type of Service', 'good'], ['Fish', 'Dolphin'], ['Shared Rooms', '4']]
result2 = [['Group', 'Jameseson'], ['Type of Service', 'bad'], ['Shared Rooms', '8']]
result3 = [['Group', 'MacIntyre'], ['Person in charge', ' Vivienne Donald (Manager)'],
['Type of Service', 'good'], ['Shared Rooms', '4'], ['Local Auth', 'bucket']]
results = [result1, result2, result3]
#Removes tuples which the first element in the tuple does not matcch any string in headers2 list
def desired_headers():
for index, z in enumerate(list(range(len(results)))):
for i in list(range(len(results[z]))):
if any(x in headers2 for x in results[z][i]):
print(index, results[z][i])
desired_headers()
当前输出:
0 ['Group', 'MacIntyre']
0 ['Person in charge', ' Vivienne Donald (Manager)']
0 ['Type of Service', 'good']
0 ['Shared Rooms', '4']
1 ['Group', 'Jameseson']
1 ['Type of Service', 'bad']
1 ['Shared Rooms', '8']
2 ['Group', 'MacIntyre']
2 ['Person in charge', ' Vivienne Donald (Manager)']
2 ['Type of Service', 'good']
2 ['Shared Rooms', '4']
期望的输出:
[[['Group', 'MacIntyre'],
['Person in charge', ' Vivienne Donald (Manager)'],
['Type of Service', 'good'],
['Shared Rooms', '4']],
[['Group', 'Jameseson'], ['Type of Service', 'bad'], ['Shared Rooms', '8']],
[['Group', 'MacIntyre'],
['Person in charge', ' Vivienne Donald (Manager)'],
['Type of Service', 'good'],
['Shared Rooms', '4']]]
【问题讨论】:
-
在
for index, z in enumerate(list(range(len(results))))索引和z值一样^^ -
顺便说一句,不要使用
list(range(...)),只使用range(...) -
元组是包含两项的非列表。你所拥有的是一个列表列表。
标签: python list for-loop indexing enumerate