简体   繁体   English

给定一个列表,我如何构造一个新列表,使得新列表的每个元素都是旧列表中每两个数字的总和?

[英]Given a list, how do I construct a new list such that every element of the new list is the sum of every two numbers in the old list?

Suppose I have a list of numbers, how do I construct a new list such that every element of the new list is the sum of every two numbers in the old list?假设我有一个数字列表,我如何构造一个新列表,使得新列表的每个元素都是旧列表中每两个数字的总和?

ie given a list of number [1,2,3,4,5,6], I would like to return the list [1+2, 3+4,5+6]=[3,7,11]即给定一个数字列表[1,2,3,4,5,6],我想返回列表[1+2, 3+4,5+6]=[3,7,11]

I have attempted to write my code in the following way.我试图用以下方式编写我的代码。 However, when I applied it to my list, I am getting the error saying list index out of range.但是,当我将它应用到我的列表时,我收到错误说列表索引超出范围。

def mod_list(mylist):
    newlist=[]    
    counter = 0
    for numbers in mylist:
        counter += 1
        if counter % 2 != 0:
            newlist.append(numbers + mylist[counter + 1])
    return newlist
[2, 0, 0, 1, 3, 0, 0, 1, 2, 2, 0, 1, 0, 0, 3, 2, 2, 0, 1, 2, 0, 4, 1, 0, 0, 0, 2, 2, 0, 1, 2, 3, 2, 1, 0, 2, 0, 0, 1, 0, 1, 1, 0, 2, 4, 1, 5, 2, 1, 4, 2, 2, 3, 1, 0, 1, 0, 5, 4, 0, 3, 1, 2, 0, 1, 1, 1, 1, 4, 1, 3, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 5, 1, 1, 2, 0, 1, 1, 1, 0, 2, 0, 0, 1, 0, 1, 1, 2, 4, 1, 0, 1, 2, 1, 0, 1, 0, 2, 6, 3, 2, 5, 4, 2, 3, 0, 1, 0, 5, 4, 2, 2, 4, 6, 1, 2, 2, 2, 0, 2, 2, 2, 2, 3, 1, 0, 0, 1, 1, 2, 1, 1, 2, 1, 4, 2, 1, 0, 7, 0, 0, 0, 2, 1, 2, 0, 0, 1, 2, 1, 0, 0, 3, 3, 4, 0, 2, 2, 2, 2, 1, 1, 5, 0, 0, 0, 3, 2, 6, 1, 0, 2, 2, 0, 0, 1, 5, 0, 0, 0, 0, 3, 1, 4, 6, 2, 3, 0, 2, 1, 6, 2, 1, 0, 4, 1, 4, 82, 17, 4, 0, 10, 8, 7, 9, 4, 2, 2, 0, 1, 1, 3, 0, 1, 3, 6, 5, 3, 1, 1, 2, 0, 0, 1, 3, 2, 1, 1, 2, 2, 0, 2, 1, 1, 0, 2, 5, 5, 1, 3, 7, 5, 3, 3, 2, 8, 4, 3, 6, 3, 2, 1, 2, 1, 3, 2, 2, 0, 2, 2, 0, 1, 0, 1, 1, 0, 0, 1, 3, 4, 3, 1, 2, 0, 0, 3, 1, 2, 2, 1, 4, 2, 0, 0, 1, 3, 1, 5, 2, 2, 2, 2, 3, 2, 2, 6, 0, 3, 3, 1, 0, 2, 1, 0, 0, 2, 0, 1, 6, 2, 1, 0, 3, 2, 1, 1, 4, 1, 6, 2, 0, 2, 2, 3, 3, 1, 6, 0, 1, 0, 0, 2, 0, 1, 5, 0, 0, 2, 1, 3, 5, 2]
Traceback (most recent call last):

  File "C:\Textbook\Physics_180A\temp.py", line 131, in <module>
    main()

  File "C:\Textbook\Physics_180A\temp.py", line 13, in main
    new_quake_days = mod_list(quake_days)

  File "C:\Textbook\Physics_180A\temp.py", line 99, in mod_list
    newlist.append(numbers + mylist[counter + 1])

IndexError: list index out of range

How can I fix this?我怎样才能解决这个问题?

zip can help here. zip可以在这里提供帮助。

We have the following data.我们有以下数据。

>>> data = [1, 2, 3, 4, 5, 6]

Now we zip the data with itself.现在我们将 zip 与自身的数据。

>>> list(zip(data, data))
[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]

Not exactly what we want, but it is a start.不完全是我们想要的,但这是一个开始。 Now we use an offset of 1 for the second parameter.现在我们为第二个参数使用1的偏移量。

>>> list(zip(data, data[1:]))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

Looks better, but we need a step of 2 .看起来更好,但我们需要一步2 This leads us to the following code.这将我们引向以下代码。

>>> list(zip(data[::2], data[1::2]))
[(1, 2), (3, 4), (5, 6)]

Now we get a list with three entries.现在我们得到一个包含三个条目的列表。 Each entry is a tuple with the numbers we want to add.每个条目都是一个包含我们要添加的数字的元组。 Now all that's left is iterating over the resulting list/iterable, do the addition and add the result to a new list.现在剩下的就是迭代结果列表/可迭代,进行添加并将结果添加到新列表中。

>>> result = []
>>> for x, y in zip(data[::2], data[1::2]):
    result.append(x + y)
    
>>> print(result)
[3, 7, 11]

This could be written as a list comprehension and that leaves us with:这可以写成列表推导式,这给我们留下了:

>>> result = [x + y for x, y in zip(data[::2], data[1::2])]
>>> print(result)
[3, 7, 11]

You can use this:你可以使用这个:

x = [1,2,3,4,5,6]
res = []
for i in range(0, len(x), 2):
    res.append(x[i] + x[i+1])

Note: This assumes that the original list has even number of elements.注意:这假设原始列表具有偶数个元素。

my_list = [1,2,3,4,5]
sum_list = []
for index, element in enumerate(my_list):
    if index+1 < len(my_list):
        sum_list.append(element+my_list[index+1])
    else:
        continue

This works for all size lists:这适用于所有尺寸列表:

list = [1, 2, 3, 4, 5]
result = []
for i in range(0, len(list), 2):
    if i == len(list) - 1:
        result.append(list[i])
    else:
        result.append(list[i] + list[i + 1])

    
print (result)

As you group items by pair, it is simpler to process lists having an even number of elements.当您按对分组项目时,处理具有偶数个元素的列表会更简单。 A trick for odd number of elements is to append a 0 : the algo will work fine, and you will get the same result:奇数元素的技巧是 append a 0 :算法可以正常工作,你会得到相同的结果:

def addlist(l):
    if len(l) % 2 != 0:
        l = l + [0]  # does not change the list in the caller
    return [l[i] + l[i+1] for i in range(0, len(l), 2)]

Demo:演示:

>>> lst = [1, 2, 3, 4, 5, 6]
>>> addlist(lst)
[3, 7, 11]
>>> lst
[1, 2, 3, 4, 5, 6]
>>> lst = [1, 2, 3, 4, 5, 6, 7]
>>> addlist(lst)
[3, 7, 11, 7]
>>> lst
[1, 2, 3, 4, 5, 6, 7]

Considering the assumption that sum is calculated for even length lists, while for odd length lists, the last element is appended to the new list as it is.考虑到总和是为偶数长度列表计算的假设,而对于奇数长度列表,最后一个元素按原样附加到新列表中。

What I mean is,我的意思是,

If the original list is [1, 2, 3, 4, 5, 6] , the output list will be [3, 7, 11] , while if the original list is [1, 2, 3, 4, 5] , the output list will be [3, 7, 5] .如果原始列表为[1, 2, 3, 4, 5, 6] ,则 output 列表将为[3, 7, 11] ,而如果原始列表为[1, 2, 3, 4, 5] , output 列表将为[3, 7, 5]

For this assumption, the code is对于这个假设,代码是

lis = [1, 2, 3, 4, 5, 6]
newLis = []
for i in range(0, len(lis), 2):
    if i < len(lis) and i + 1 < len(lis):
        newLis.append(lis[i] + lis[i + 1])
    else:
        newLis.append(lis[i])

For odd-length list, if the last element is not required, the else part maybe removed.对于奇数长度列表,如果最后一个元素不是必需的,则可以删除 else 部分。

How about making an iterable and extracting two elements from it in each iteration?如何制作一个可迭代的并在每次迭代中从中提取两个元素? Giving next a default value of 0 deals with odd cases.next一个默认值 0 处理奇数情况。

As a bonus, you do not need to create intermediate lists or use an explicit if-else.作为奖励,您不需要创建中间列表或使用显式 if-else。

def mod_list(mylist):
    list_iter = iter(mylist)
    return [x + next(list_iter, 0) for x in list_iter]

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

相关问题 如何对列表中的每个元素求和? - How do a sum a value to every element in a list? 列表中每个元素的总和 - Sum of every element in a list 列表中所有其他元素的总和 - Sum of every element with every other element in a list 每次元素更改时如何获取新列表(元素是元组列表中每个元组的特定索引) - How to get a new list every time an element changes (the element being a certain index for every tuple in a list of tuples) Python:对于列表中的每个元素,获取一个没有该元素的新列表 - Python: for every element in list get a new list without that element 我有两列,其中包含列表。如何将这两个列表组合成元素的新列元素 - I have two columns with list in in. How do I combine these two list into a new column element for element 使用 for 循环为另一个列表的每个元素创建一个新列表 - Create a new list for every element of another list with for loops 在给定 2 个数字的情况下找到填充 3 元素列表的所有方法 - Find every way to fill a 3 element list given 2 numbers 通过从两个列表中的任何一个中删除第一个元素并附加到新列表来查找每个可能的列表 - Finding every possible list made by removing the first element from either of two lists and appending to the new list 每个While循环都有新列表 - New list every While loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM