Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.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 将多行合并为一行_Python_Algorithm - Fatal编程技术网

Python 将多行合并为一行

Python 将多行合并为一行,python,algorithm,Python,Algorithm,这是我期末考试中遇到的一道难题,我无法找到解决办法。这已经困扰了我好几天了,我想我会在这里发布一些指导/建议 问题如下:您有一个元组列表(a),元组是字符串和数字。问题是“迭代数据集,将带有空字符串的行的值附加到最近的非空字符串的值集”。最后的结果应该看起来像b数组 a = [ ('Hello', 1), ('', 2), ('', 3), ('', 4), ('World', 1), ('', 2)] b = [ ("Hello", [

这是我期末考试中遇到的一道难题,我无法找到解决办法。这已经困扰了我好几天了,我想我会在这里发布一些指导/建议

问题如下:您有一个元组列表(a),元组是字符串和数字。问题是“迭代数据集,将带有空字符串的行的值附加到最近的非空字符串的值集”。最后的结果应该看起来像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)
您可以这样做:

其思想是使用字典将属于每个字符串的所有值存储在一个列表中,然后迭代字典的键

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)
您可以这样做:

其思想是使用字典将属于每个字符串的所有值存储在一个列表中,然后迭代字典的键

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)
输出:

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

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