2024-10-05 14:29:42 发布
网友
我有这样一个元组列表:
myList=[(u"hell world", 10),(u"hello mom", 20), (u"hello dad","5")]
我需要修改每个元组以获得如下列表:
mySecondList= [(u"hell",u"world","10"),(u"hello",u"mom","20"), (u"hello",u"dad","5")]
我该怎么做?你知道吗
元组是一种不可变的类型,因此一旦创建它们,就无法更改内容。也许你应该试试列表,它是可变的。你知道吗
您可以使用列表理解表达式实现所需的行为:
[tuple(item[0].split() + [str(item[1])]) for item in myList]
它将返回:
[(u'hell', u'world', '10'), (u'hello', u'mom', '20'), (u'hello', u'dad', '5')]
注:^{}在本质上是不变的。不能修改现有的元组对象。在这里,我返回新的列表和新创建的元组对象
正如我在评论中所写,元组是不可变的,但您可以使用以下代码:
def modify(lst): ret = [] for tpl in lst: ret.append(tuple([tpl[0].split(' '), tpl[1]])) return ret
若要传递构造函数或使用cd1,请执行以下操作:
new_list = tuple(item[0].split(' ') + [item[1]]) for item in myData)
元组是一种不可变的类型,因此一旦创建它们,就无法更改内容。也许你应该试试列表,它是可变的。你知道吗
您可以使用列表理解表达式实现所需的行为:
它将返回:
注:^{} 在本质上是不变的。不能修改现有的元组对象。在这里,我返回新的列表和新创建的元组对象
正如我在评论中所写,元组是不可变的,但您可以使用以下代码:
若要传递构造函数或使用cd1,请执行以下操作:
相关问题 更多 >
编程相关推荐