将名字列表与名字列表结合起来以创建全名

时间:2019-08-21 11:18:56

标签: python-3.x

我目前有2个列表:一个带有名字,另一个带有姓氏。

列表中有200个元素,每个元素最多可以有5个名字。

列表2的姓氏与列表中相同位置的名字完全相同。

我想合并两个列表并创建全名。

list1看起来像这样:

-Index   -Type    -Size    -Value
- 0      -list    -4       -['Robert', 'Bruce', 'George', 'Gavin']
- 1      -list    -2       -['Aaron', 'Fred']

list2看起来像这样:

-Index    -Type    -Size    -Value
- 0       -list    -4       -['Leslie', 'Scott', 'Smith', 'King']
- 1       -list    -2       -['Weston', 'Cranswick']

我想实现的是这样:

-Index    -Type    -Size   -Value
- 0       -list    -4      -['Robert Leslie', 'Bruce Scott', George Smith',.....']
- 1       -list    -2      -['Aaron Weston', 'Fred Cranswick']

我尝试仅将列表加在一起:

Full_Name = First_Name + Last_Name

但是不幸的是,这不是那么简单

3 个答案:

答案 0 :(得分:0)

您必须遍历其中一个与另一个具有相同索引的矩阵连接的矩阵,例如:

for i, list in enumerate(first_name_lists):
  for j, first_name in enumerate(list):
    first_name = first_name + ' ' + last_name_lists[i][j]

答案 1 :(得分:0)

除非我有误解,否则您应该能够使用索引来迭代列表并像这样加入?

first_names_1 = ['Robert', 'Bruce', 'George', 'Gavin']
first_names_2 = ['Aaron', 'Fred']

last_names_1 = ['Leslie', 'Scott', 'Smith', 'King']
last_names_2 = ['Weston', 'Cranswick']

def join_arrays(first_names, last_names):

    full_names = []

    if len(last_names) == len(first_names):
       for index in range(0,len(first_names)):
            full_names.append("{} {}".format(first_names[index], last_names[index]))


    return full_names

full_names = join_arrays(first_names_1, last_names_1) + join_arrays(first_names_2, last_names_2)

print("{}".format(full_names))

答案 2 :(得分:0)

[[' '.join(name for name in names) for names in zip(pair[0],pair[1])] for pair in zip(list1, list2)]

此行将连接两个以空格分隔的列表的嵌套元素。

示例代码

list1 = [['Robert', 'Bruce', 'George', 'Gavin'], ['Aaron', 'Fred'], ["Alif"]]
list2 = [['Leslie', 'Scott', 'Smith', 'King'], ['Weston', 'Cranswick'], ["King"]]

fullnames = [[' '.join(name for name in names) for names in zip(pair[0],pair[1])] for pair in zip(list1, list2)]

输出:

fullnames = [['Robert Leslie', 'Bruce Scott', 'George Smith', 'Gavin King'],
     ['Aaron Weston', 'Fred Cranswick'],
     ['Alif King']]