Python:更改元组列表中的元组

标签 python list tuples

我正在尝试替换元组列表中元组中的值。

recordlist = [(sku,item,bro),(sku1,item1,bro1),...]

for item in recordlist:
    itemlist = list(item)
    if itemlist[0] == 'sku':
        itemlist[1] = itemlist[1]+',item'
        item = tuple(itemlist)

        print(item)

此代码目前无法运行。有人可以帮忙吗? 当前输出显示

('sku','item','bro')

预期输出是:

('sku','item,item','bro')

最佳答案

我认为将更新的元组分配给列表中的相应索引将解决问题,因为元组是不可变的。为了保留相应的索引,可以在迭代列表时使用enumerate。您可以尝试以下操作:

recordlist = [('sku1','item1','bro1'),('sku2','item2','bro2')]

for index, item in enumerate(recordlist):
    itemlist = list(item)
    if itemlist[0] == 'sku1':
        itemlist[1] = itemlist[1]+','+'item'
    item = tuple(itemlist)

    recordlist[index] = item

print(recordlist)

输出:

[('sku1', 'item1,item', 'bro1'), ('sku2', 'item2', 'bro2')]

关于Python:更改元组列表中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44751916/

相关文章:

python - 判决是什么?在我的模型或模型表单中验证?

c++ - QML listview读取当前和触摸区域

python - 如何定义一组变量,以便程序响应列表中的任何项目被调用,python3

python - 从包含元组值的字典中查找最小值和最大值

python - 如何在没有 python 的情况下(交叉)编译 boost?

python - 如何在 tox 中要求特定的软件包版本?

python - 在设置 View 集时,出现错误 AttributeError : 'function' object has no attribute 'get_extra_actions'

python - 排列和索引,python

c++ - 使用折叠表达式构造平凡对象

c# - 元组与类有何不同?