簡體   English   中英

Python從while循環中將元組加入列表

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

我正在遍歷表單的大量元組

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

我正在嘗試為第一個元素的每個不同值在第二個元素的5個滾動值周期內找到每個元組的最大第四個元素,所有不同的第一個元素值都存儲在一個名為account_2的集合中,並將其輸出到形成

ID   Max
A21  400
A15  489

我的代碼如下:

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

我想我需要用num_list[0][0]的第1個0代替要循環的變量,以便它循環遍歷列表中的每個元組,但是在我測試的第一個元組中,即在當前情況下收到錯誤TypeError: 'tuple' object does not support item assignment

任何幫助將不勝感激。 提前致謝

錯誤是由行引起的

for num_list[0][0] in account_2:

它嘗試將值從account_2分配給numlist[0][0]numlist[0]是一個元組,這是一個不可變的對象。

最小修復為:

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

try: ... except...是必需的,因為在傳遞空序列時max會引發ValueError。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM