Python:更改元组列表中的元组 [英] Python: Change tuple in a list of tuples

查看:56
本文介绍了Python:更改元组列表中的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to replace a value in a tuple in a list of 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)

此代码当前不起作用.有人可以帮忙吗?当前输出显示

This code currently is not working. Can someone help? the current output shows

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

预期输出为:

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

推荐答案

我认为将更新的 tuple 分配给 list 中的相应索引将解决问题,因为 <代码>元组是不可变的.为了保持相应的索引 enumerate 可以在遍历列表时使用.您可以尝试以下操作:

I think assigning the updated tuple to the corresponding index in the list will solve the issue since tuples are immutable. To keep the corresponding index enumerate can be used while iterating through the list. You can try following:

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:更改元组列表中的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆