如何将一个值附加到列表中的每个元组?

时间:2014-01-29 05:43:45

标签: python list append tuples sublist

如何将1个值附加到列表中的每个元组?

 tuple_list = [('a','b'),('c','d'),('e','f')]
 value = 111


 Desired_List = [(111,'a','b'),(111,'c','d'),(111,'e','f')]

我尝试过以下方法:

   for x in tuple_list:
        x.append(111)

   for x in tuple_list:
        x + '111'

我更喜欢子列表而不是元组,所以无论如何也要将元组更改为子列表?

注意: 111是在第一个索引中还是在元组的最后一个索引中实际上并不重要。

3 个答案:

答案 0 :(得分:8)

您可以使用列表推导来完成您要做的两件事。

前缀:

desired_list = [[value]+list(tup) for tup in tuple_list]

后缀:

desired_list = [list(tup)+[value] for tup in tuple_list]

list()调用会将每个元组转换为一个列表,添加另一个仅包含value的列表会在创建每个列表后将该值添加到每个列表中。

答案 1 :(得分:1)

使用map

>>> tuple_list = [('a','b'),('c','d'),('e','f')]
>>> map(list, tuple_list)
[['a', 'b'], ['c', 'd'], ['e', 'f']]

或列表理解。

>>> [list(elem) for elem in tuple_list]
[['a', 'b'], ['c', 'd'], ['e', 'f']]

由于您所需的输出是元组列表,您可以这样做。

>>> [(111,) + elem for elem in tuple_list]
[(111, 'a', 'b'), (111, 'c', 'd'), (111, 'e', 'f')]

答案 2 :(得分:1)

您可以为此使用带有lambda函数的map

new_list = map(lambda x: [111] + list(x), tuple_list)