【问题标题】:Python joining tuples from a while loop into a listPython将来自while循环的元组加入列表
【发布时间】:2018-10-25 00:33:51
【问题描述】:

我正在遍历表单的大量元组

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] 中的第一个0 替换为要循环的变量,以便循环遍历列表中的每个元组,但在我仅测试第一个元组时,即在当前情况下,我'我收到错误TypeError: 'tuple' object does not support item assignment

任何帮助将不胜感激。提前致谢

【问题讨论】:

  • num_list[0][0] += (your_new_val,)
  • 每个元组只包含一个“第四个元素”,那么最大的第四个元素是什么意思?第二个元素的滚动 5 值周期如何具有第四个元素?

标签: python list tuples typeerror


【解决方案1】:

错误是由线路引起的

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。

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 2021-11-13
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多