如何在嵌套列表中一起添加元素?

时间:2019-12-18 20:47:05

标签: python-3.x for-loop while-loop nested-lists

我正在尝试将.csv文件中嵌套列表中人员的姓氏和名字加在一起。我的数据如下所示: Picture of data spreadsheet

我的列表peopleNames具有以下当前输出:

[['Barreuther', 'Mark', '', '', '', '', '', '', '', '', '', '', '', '', '', ''], ['Demaio', 'Daniel', 'Certo', 'Catherine', 'Frankel', 'Stewart', 'Levesque', 'Aime', 'Mahan', 'Eric J.', 'Rosiene', ' Pe', 'Haruta', 'Mako E.', '', '']... many more lists]

我想将彼此相邻的两个字符串加在一起。例如[['Barreuther Mark']]。我尝试了以下代码:

def getInfo():
"""Open csv, read it, get nested list, separate names and schools, return two lists"""

#
with open("CT_schools.csv") as f:
    reader = csv.reader(f)
    data = []
    #start for
    for row in reader:
        data.append(row)               
    #end for

    schoolNames = []
    peopleNames = []

    #start for
    for i in range(len(data)):
        schoolNames.append(data[i][0])
        peopleNames.append(data[i][1:])
    #end for

    index = 0
    name = 0
    NewpeopleNames = []
    #start while
    while index < len(peopleNames):
        for i in range(len(peopleNames)):
            fullName = peopleNames[index][i] + " " + peopleNames[index][i+1]
        NewpeopleNames.append(fullName)
        index = index + 1
        name = name + 2

我得到以下输出:

[”,“ Pe Haruta”,“ Ronald Golbazi”,“ Christoph Raskin”,“,”,“ Barry Oliver”,“,”,“,”,“ Douglad M.” ]

然后我将while循环替换为嵌套的for循环:

#start nested for
    for index in range(len(peopleNames)):
        for name in range(len(peopleNames[index])):
            fullName = peopleNames[index][name] + peopleNames[index][name + 1]

然后我收到一条错误消息,指出它不在列表的索引中。您认为有人可以尝试指出正确的方向吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

嵌套循环是一种幼稚的解决方案(如果您不喜欢代码的复杂性)。

我建议首先从列表中过滤掉所有空值,然后才引用“将彼此相邻的两个字符串相加”。

NewPeopleNames = list()
for sub_list in peopleNames:
    tmp_list = list()
    filtered_list = list(filter(None, sub_list))
    for i in range(0, len(filtered_list), 2):
        if i+1 >= len(filtered_list):
            print('There is no last name for \'{0}\''.format(filtered_list[i]))
            continue
        tmp_list.append('{0} {1}'.format(filtered_list[i], filtered_list[i+1]))
    NewPeopleNames.append(tmp_list)

请注意,列表大小不一(名字和姓氏没有)有一些“保护”。

您可以修改打印行,以仅将名称(filtered_list [i])附加到NewPeopleNames列表中。