简体   繁体   English

从列表列表中创建一个列表,对 enumerate 方法创建的每个列表使用相同的重复索引号

[英]Making a list from a list of lists, using the same repeated index number for each list created by the enumerate method

My function desired_headers() removes tuples from "results" object which the first element in the tuple does NOT match any string in headers list.我的 function desired_headers() 从“结果” object 中删除元组,其中元组中的第一个元素与标题列表中的任何字符串都不匹配。 ['Fish', 'Dolphin'] from result1 object & ['Local Auth', 'bucket'] has been removed from result3. ['Fish', 'Dolphin'] from result1 object & ['Local Auth', 'bucket']已从 result3 中删除。

Then it prints the index number and list of tuples as seen under current output below.然后它打印索引号和元组列表,如下面的当前 output 所示。

My aim is to "repack" the lists of tuples back together using my current output and store in an object.我的目标是使用我当前的 output 将元组列表“重新打包”并存储在 object 中。

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

Current Output:当前 Output:

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

Desired Output:所需的 Output:

[[['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']]]

You need something like this?你需要这样的东西吗? This will group everything in a single list这会将所有内容分组在一个列表中

# Removes tuples which the first element in the tuple does not matcch any string in headers2 list
def desired_headers():
    grouped_elements = []
    for index, z in enumerate(list(range(len(results)))):
        inner_loop = []
        for i in list(range(len(results[z]))):
            if any(x in headers2 for x in results[z][i]):
                inner_loop.append(results[z][i])

        grouped_elements.append(inner_loop)

    print(grouped_elements)

Try this尝试这个

lv1 = [] # initialize an empty list which we will append to based on our criteria

for lst in results: # loop though each element of the list, which itself is a list
    lv2 = []
    for el in lst: # Same as above
        if el[0] in headers2: # check if first element of the list exists in headers2
            lv2.append(el)
    lv1.append(lv2)

lv1

Or if you want a function或者如果你想要一个 function


def desired_headers(list_of_lists, inclution_list):
    lv1 = []

    for lst in list_of_lists:
        lv2 = []
        for el in lst:
            if el[0] in inclution_list:
                lv2.append(el)
        lv1.append(lv2)

    return lv1

desired_headers(list_of_lists=[result1, result2, result3], inclution_list=headers2)

Or if you are familiar with list comprehentions或者,如果您熟悉列表理解

result = [] 

for lst in [result1, result2, result3]:
    result.append([el for el in lst if el[0] in headers2])

result 

You could do it with a list comprehension:您可以通过列表理解来做到这一点:

filtered = [ [sl for sl in r if sl[0] in headers2] for r in results ]

output: output:

print(filtered)

[
    [
        ['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']
    ]
]

If you have a lot of data, you may want to make a set out of headers2 to use in the list comprehension如果您有大量数据,您可能希望使用headers2来制作一组用于列表理解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 enumerate 获取列表列表 (json) - Using enumerate for a list of lists (json) 从元组列表生成具有相同元组数和索引的列表范围 - Generate range of lists with the same number of tuples and index from list of tuples 枚举列表和排序列表 - Enumerate List of Lists and Sorting 从两个列表开始,如何将每个列表中相同索引的元素放入元组列表 - Starting from two lists, how to put the elements of the same index from each list into a list of tuples 有没有办法枚举共享相同索引的列表或词典? - Is there a way to enumerate a list or dictionary that share the same index? python list comprehension:从列表列表中的每个列表中创建多个项目的列表 - python list comprehension: making list of multiple items from each list within a list of lists 在列表列表中查找每个列表的最小值的索引 - Finding the index of the minimum of each list in a list of lists 列表列表或多个列表可以元素组合的所有方式是什么 - 对每个列表中具有相同索引的项目进行操作? - What are all the ways that a list of lists or multiple lists can be combined elementwise - operate on the items from each list with the same index? 了解带有列表的枚举的reduce - Understanding reduce with enumerate for a list of lists 从列表清单制作字典 - Making a dictionary from a list of lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM