简体   繁体   English

Python从while循环中将元组加入列表

[英]Python joining tuples from a while loop into a list

I'm iterating over a large list of tuples of the form 我正在遍历表单的大量元组

num_list = [('A15', 2, 'BC', 721.16), ('A21', 3, 'AB', 631.31), ('A42', 4, 'EE', 245.43)]

I'm trying to find the maximum fourth element of each tuple over a rolling 5 value period for the second element for each different value of the first element, all the different first element values are stored in a set called account_2 and output that in a form 我正在尝试为第一个元素的每个不同值在第二个元素的5个滚动值周期内找到每个元组的最大第四个元素,所有不同的第一个元素值都存储在一个名为account_2的集合中,并将其输出到形成

ID   Max
A21  400
A15  489

My code is below: 我的代码如下:

first_value = 1
fifth_value = 5
maximum = []    

while first_value <= 24 and fifth_value <= 28:
    for num_list[0][0] in account_2:
        result = max([i for i in num_list if i[1] <= fifth_value and i[1] >= first_value], key = lambda  x:x[3])
        maximum.extend(result)
        first_value += 1
        fifth_value += 1

I think I need to substitute the 1st 0 in num_list[0][0] for a variable to loop over so it loops over every single tuple in the list but in my testing of just the first tuple ie in the current case I'm getting the error TypeError: 'tuple' object does not support item assignment . 我想我需要用num_list[0][0]的第1个0代替要循环的变量,以便它循环遍历列表中的每个元组,但是在我测试的第一个元组中,即在当前情况下收到错误TypeError: 'tuple' object does not support item assignment

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks in advance 提前致谢

The error is caused by the line 错误是由行引起的

for num_list[0][0] in account_2:

which tries to assign values from account_2 to numlist[0][0] while numlist[0] is a tuple, that is an immutable object. 它尝试将值从account_2分配给numlist[0][0]numlist[0]是一个元组,这是一个不可变的对象。

The minimum fix would be: 最小修复为:

while first_value <= 24 and fifth_value <= 28:
    for acc in account_2:
        try:
            result = max([i for i in num_list if i[1] <= fifth_value and i[1] >= first_value and i[0] == acc ], key = lambda  x:x[3])
        except ValueError:
            result = ()
        maximum.extend(result)
        first_value += 1
        fifth_value += 1

The try: ... except... is necessary because max raises a ValueError when it is passed an empty sequence. try: ... except...是必需的,因为在传递空序列时max会引发ValueError。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM