将多行合并为单行

时间:2018-12-27 16:45:58

标签: python algorithm

这是我在期末考试中遇到的一个特殊性难题,无法解决。它困扰了我好几天了,我想我会在这里发布一些指导/建议。

问题如下:您有一个由字符串和数字组成的元组列表。这个问题说“迭代数据集,将带有空字符串的行的值附加到最新的非空字符串的值集上”。最终结果应该看起来像b数组

a = [
    ('Hello', 1),
    ('', 2),
    ('', 3),
    ('', 4),
    ('World', 1),
    ('', 2)]

b = [
    ("Hello", [1, 2, 3, 4]),
    ("World", [1, 2])]


data = iter(a)

for row in data:
    lastKey = ''
    carryValues = []

    if not row[0] == '':
        lastKey = row[0]
    else:
        while row[0] == '':
            carryValues.append(row[1])
            row = next(data, None)

    print(lastKey, carryValues)

2 个答案:

答案 0 :(得分:1)

您可以这样做:

想法是使用字典将列表中每个字符串的所有值存储在列表中,然后遍历字典的键

last_key = ''
sol_dict = {}
lst =  [
    ('Hello', 1),
    ('', 2),
    ('', 3),
    ('', 4),
    ('World', 1),
    ('', 2)]


for tup in lst:
    if tup[0] != '':
        last_key = tup[0]
        sol_dict[last_key] = [tup[1]]
    else:
        sol_dict[last_key].append(tup[1])


result_list = []

for key in list(sol_dict.keys()):
    result_list.append((key,sol_dict[key]))

print (result_list)

答案 1 :(得分:1)

a = [
('Hello', 1),
('', 2),
('', 3),
('', 4),
('World', 1),
('', 2)] 

b = []

i = 0

for row in a:
    if row[0]!='':
        b.append((row[0], [row[1]]))
        i = i + 1
    else:
        b[i-1][1].append(row[1])
print(b)

输出:

[('Hello', [1, 2, 3, 4]), ('World', [1, 2])]