简体   繁体   English

如果列表中的元素数大于 2,则将列表前半部分中的 n 个元素与列表另一半中的元素组合

[英]Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2

I have a problem with dealing with elements in a list.我在处理列表中的元素时遇到问题。 To be precise in a list of lists.准确地说是在列表列表中。 For example, I have list of elements that are read from a file:例如,我有从文件中读取的元素列表:

list_1 = [['void', None], ['uint8', 'f_MbistTestType_u8'], ['uint8', 'uint32', 'f_MbistTestType_u8', 'f_chip_id_u32'], ['void', None], ['void', None], ['void', None], ['void', None]]

In this case third element has more than two elements.在这种情况下,第三个元素有两个以上的元素。 I want to switch element 2 with element 3. So it would look like this:我想用元素 3 切换元素 2。所以它看起来像这样:

list_1[2] = ['uint8', 'f_MbistTestType_u8', 'uint32', 'f_chip_id_u32']

If there would be 6 elements ie如果有 6 个元素,即

list_example = ['uint8', 'uint32', 'void', 'f_chip_id_u32', 'f_MbistTestType_u8', None]

After the operation it should look like this:操作后应该是这样的:

list_example_sorted = ['uint8', 'f_chip_id_u32', 'uint32', 'f_MbistTestType_u8', 'void', None]

Right now I know how to get those elements in case I have only one occurrence of more than 2 elements, but don't know how to switch their places and also what to do in case I have more than one occurrence:现在我知道如何获取这些元素,以防我只出现一次超过 2 个元素,但不知道如何切换它们的位置,也不知道如果出现不止一次该怎么做:

for elements in list_1:
print(elements)
if len(elements) > 2:
    list_el = elements
    print(list_el)

I tried to pop them out and append, but it won't scale well with more than 4 elements.我试图弹出它们和 append,但它不能很好地扩展超过 4 个元素。

I tried to use swap function, but it seems that it doesn't work or I used it wrong?我试过用swap function,但是好像不行还是我用错了?

在此处输入图像描述

Going by an input of [1, 1, 1, 2, 2, 2] with the desired output [1, 2, 1, 2, 1, 2] , ie you want the first element of the left half followed by the first element of the right half and so forth.通过输入[1, 1, 1, 2, 2, 2]和所需的 output [1, 2, 1, 2, 1, 2] ,即您想要左半部分的第一个元素,然后是第一个右半部分的元素等等。 To make it more obvious:为了使它更明显:

  • input = [1, 2, 3, 4, 5, 6]
  • output = [1, 4, 2, 5, 3, 6]

Define a function combine_inplace that combines the ith element of the left half with the ith element of the right half of l :定义一个 function combine_inplace ,它将左半部分的第 i 个元素与l右半部分的第 i 个元素组合在一起:

def combine_inplace(l):
    mid = len(l) // 2
    ptr = 0
    for left, right in zip(l[:mid], l[mid:]):
        l[ptr], l[ptr+1] = left, right
        # Increment pointer ptr by 2 for the next combination
        ptr += 2
  • combine_inplace mutates the passed list l combine_inplace改变传递的列表l
  • left half and right half are created using slice operator左半部分和右半部分是使用切片运算符创建的
  • use zip to iterate over both list使用zip遍历两个列表
  • increment ptr by 2 to get to the next list indices for lptr递增 2 以获得l的下一个列表索引

If you don't want to mutate the list itself you can instead create a new list combined that is returned by the function combine :如果您不想改变列表本身,您可以创建一个由 function combine返回的新combined列表:

def combine(l):
    mid = len(l) // 2
    combined = []
    for left, right in zip(l[:mid], l[mid:]):
        combined.extend((left, right))
    return combined
  • Does not mutate the passed list l不改变传递的列表l
  • Initialise empty list combined to store the combined values初始化combined的空列表以存储组合值
  • use zip to iterate over both list halves使用zip遍历列表的两半
  • Returns the list combined返回combined列表

This uses the same logic as combine_inplace but you keep the original list intact.这使用与combine_inplace相同的逻辑,但您保持原始列表不变。

Both functions combine the elements of the left half with the right half of a given list.这两个函数都将给定列表的左半部分和右半部分的元素组合在一起。 The only difference is that with combine you have to store the returned list in a variable to access it.唯一的区别是使用combine你必须将返回的列表存储在一个变量中才能访问它。

>> l = [1, 1, 1, 2, 2, 2]
>> combine_inplace(l)
>> print(l)
[1, 2, 1, 2, 1, 2]
>> input_list = [1, 2, 3, 4, 5, 6]
>> output_list = combine(input_list)
>> print(output_list)
[1, 4, 2, 5, 3, 6]

Now using either combine or combine_inplace to combine elements of lists with a length > 2 inside a list:现在使用combinecombine_inplace将列表中length > 2的元素组合到列表中:

ll = [[1, 2], [1, 2], [1, 1, 2, 2], [1, 2], [1, 2, 3, 4, 5, 6]]
# Non-destructive way using combine to create a new list comb_ll
comb_ll = []
for el in ll:
    if len(el) > 2:
        el = combine(el)
    comb_ll.append(el)

# Mutates the original list
for i in range(len(ll)):
    if len(ll[i]) > 2:
        combine_inplace(ll[i])

In both cases you'll get the same result:在这两种情况下,您都会得到相同的结果:

>> print(comb_ll)
[[1, 2], [1, 2], [1, 2, 1, 2], [1, 2], [1, 4, 2, 5, 3, 6]]
>> print(ll)
[[1, 2], [1, 2], [1, 2, 1, 2], [1, 2], [1, 4, 2, 5, 3, 6]]

暂无
暂无

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

相关问题 前一半与后一半的单列表轮换,包括奇数个元素 - Single list rotation of the first half with the other half, including odd number of elements 找到列表中元素总和减半的最小步骤数,其中每个步骤将列表中的项目减半 O(N) - Find the minimum number of steps to half the sum of elements in a list where each step halves an item in the list in O(N) 列表中的元素大于或等于其他列表中的元素(没有 for 循环?) - Elements in list greater than or equal to elements in other list (without for loop?) 当 n 大于列表中元素的数量时,旋转列表 n 次 - Rotating a list n times when n is greater than the number of elements in list 获取列表中所有重复元素的一半 - get half of all repeating elements in a list 提取所有大于 'm' 且小于 'n' 的列表元素 - Extract all the list elements that are greater than 'm' and less than 'n' 如果列表中的最后n个元素大于一个数字,则返回列表中的剩余项 - Return remaining items in list, if last n elements in list greater than a number 如何将列表分成 4 个一组,其中第一个元素大于最后一个? - How to split a list into groups of 4 where first elements are greater than the last? 将列表移至其他列表一半大小以获取公共元素 - Moving a list half its size against other list to get the common elements Python-如何生成大小大于列表元素个数的排列 - Python - How to generate permutations of size greater than the number of list elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM