Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 函数将每个列表中的前2个元素连接到列表列表中_Python_Python 3.x_List - Fatal编程技术网

Python 函数将每个列表中的前2个元素连接到列表列表中

Python 函数将每个列表中的前2个元素连接到列表列表中,python,python-3.x,list,Python,Python 3.x,List,我有以下清单: listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']] ^^这只是一个例子,在我的列表列表中,我将有更多相同格式的列表。 这将是我想要的输出: listoflist = [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCAT

我有以下清单:

listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]
^^这只是一个例子,在我的列表列表中,我将有更多相同格式的列表。 这将是我想要的输出:

listoflist = [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]
基本上,在每个列表中,我希望将第一个索引与第二个索引连接起来,在一个索引中形成一个全名,如示例中所示。
我需要一个函数,让谁来输入一个列表,我怎么能用一种简单的方式来做呢?(我不需要额外的库)。我使用python 3.5,非常感谢您抽出时间

您可以遍历外部列表,然后连接前两个项目的切片:

def merge_names(lst):
   for l in lst:
      l[0:2] = [' '.join(l[0:2])]

merge_names(listoflist)
print(listoflist)
# [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

这个简单的列表理解应该可以做到:

res = [[' '.join(item[0:2]), *item[2:]] for item in listoflist]
连接列表中的前两项,并按原样附加其余项。

您可以尝试以下操作:

f = lambda *args: [' '.join(args[:2]), *args[2:]]

listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

final_list = [f(*i) for i in listoflist]
输出:

[['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

您也可以使用列表理解:

listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

def f(lol):
  return [[' '.join(l[0:2])]+l[3:] for l in lol]

listoflist = f(listoflist)
print(listoflist)
# => [['BOTOS AUGUSTIN', 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 'February 2015', 600, 'ALOCATIA']]

为什么要投否决票?这将改变原来的列表,这可能是一个好主意!这很有效,这正是我需要的,谢谢你,先生!我不得不接受你的答复,因为这是一个快速和正确的!只是一个问题,您不需要在函数末尾返回,我的意思是,返回lst?@TatuBogdan Nope。我正在修改列表,因此原始引用仍然有效。返回将强制您对输出进行赋值,如果使用相同的名称,则该赋值可能是冗余名称重新绑定。OTOH,就地修改列表更快更有效。