【问题标题】:How to add elements in one list to another?如何将一个列表中的元素添加到另一个列表中?
【发布时间】:2020-08-03 23:13:06
【问题描述】:

这可能不是 SO 社区普遍接受的问题。我是一个 12 岁的初学者 Python 编码器,我正在从事这个项目,以收集跨多个网站和 GitHub 帖子的 Corona 统计数据。然后我会把它变成一个图表。一些已创建的列表将由一个国家但在不同的省份生成。所以我需要做的就是将列表中的每个元素添加到列表中的另一个元素中,这样我就可以只有一个国家列表。 我已将两个或多个列表附加到一个名为 full 的列表中并对其进行了一些格式化,它看起来有点像这样:

['China', '  8', '  8', '  8', '  8', '  8', '  8', '  8', 
 'China', '  2', '  2', '  2', '  2', '  2', '  2', '  2', 
 'China', '  6', '  6', '  6', '  6', '  6', '  6', '  6', 
 'China', '  22', '  22', '  22', '  22', '  22', '  22', '  22']

我的目标


因此,例如,我需要将 8 添加到 2 并将其放入列表中:

现在很简单:

list1 = full[1]+full[3]

但是,如果我需要将列表中的多个元素相互添加并且每次都不同的完整列表数量(我的列表)(这会发生,因为中国可能有 8 个省,所以我创建了 8 个列表,而印度有 50 个省份,所以我创建了 50 个列表)。

结果


所以这就是我想得到但无法弄清楚的。
['China', '8','7','2', 'China','2','34','18']
['India', '8','7','2', 'India','2','34','8','India','2','231','44']

China = ['10','41','20']
India = ['12','271','55']

这是我的代码:

file = open('similar.txt','r')
L = []
full = []
final = []
countryName = ''
numfinal = 0
for row in file:
    count = 1
    row = row[:-2]
    row = row[1:]
    L.append(row)
    for i in L:
        L = i.split(',')
    L = [i.replace('\n','')for i in L]
    L = [i.replace('\'','') for i in L]  

    if L[0] == countryName:
        for i in L:
            full.append(i)
        print(full)
    else:
        countryName = L[0]
        full.clear()

(还有更多,但这些文件对我的问题无关紧要。它还从一个文件中读取,该文件包含所有省份以上的国家。粘贴有点太多,所以我在下面有一个卷曲) curl-O'https://raw.githubusercontent.com/BuddyBob/Py_Programs/master/Hackathon/Deaths/similar.txt' 或者只是使用链接。任何帮助将不胜感激

这是来自similar.txt的几行:

['Australia', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0']
['Australia', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4']
['Australia', ' 83', ' 92', ' 105', ' 112', ' 116', ' 123', ' 123']
['Canada', ' 7', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8']
['Canada', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3']
['Canada', ' 2807', ' 2812', ' 2813', ' 2816', ' 2819', ' 2821', ' 2822']
['Canada', ' 5667', ' 5670', ' 5670', ' 5673', ' 5674', ' 5678', ' 5681']
['China', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1']
['China', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8']

【问题讨论】:

  • 您需要使用+one_list.extend(another_list) 将两个列表连接到一个新列表中,以便将another_list 中的值放入one_list。检查the docs。我建议不要在一个平面列表中混合不同种类的项目;考虑像@​​987654332@ 这样更容易操作的结构。
  • 每个列表都是他们自己的国家吗?每个国家的整数数量是否相同?
  • 你能从similar.txt文件中发布几行吗?
  • @jab 是的,我将以中国的每个省份为例,添加每个元素以创建 1 个与列表 1 或 2 长度相同的列表。每个国家都有相同数量的整数(7)
  • @9000 我一定会发几个

标签: python list add


【解决方案1】:

下面是对数据进行分组和求和的一种方法的说明。肯定有更短更花哨的方法来做这种事情,但这个例子打破了这些步骤。

import json

# Your lists.
raw_lists = [
    ['Australia', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0'],
    ['Australia', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4'],
    ['Australia', ' 83', ' 92', ' 105', ' 112', ' 116', ' 123', ' 123'],
    ['Canada', ' 7', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8'],
    ['Canada', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3'],
    ['Canada', ' 2807', ' 2812', ' 2813', ' 2816', ' 2819', ' 2821', ' 2822'],
    ['Canada', ' 5667', ' 5670', ' 5670', ' 5673', ' 5674', ' 5678', ' 5681'],
    ['China', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1'],
    ['China', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8', ' 8'],
    ['China', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2'],
    ['China', ' 6', ' 6', ' 6', ' 6', ' 6', ' 6', ' 6'],
    ['China', ' 22', ' 22', ' 22', ' 22', ' 22', ' 22', ' 22'],
    ['China', ' 4512', ' 4512', ' 4512', ' 4512', ' 4512', ' 4512', ' 4512'],
    ['China', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1'],
    ['China', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1'],
    ['China', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2'],
    ['China', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0'],
    ['China', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3'],
    ['China', ' 7', ' 7', ' 7', ' 7', ' 7', ' 7', ' 7'],
    ['China', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3'],
    ['China', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0', ' 0'],
    ['China', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2', ' 2'],
    ['Denmark', ' 613', ' 613', ' 614', ' 615', ' 615', ' 615', ' 615'],
    ['France', ' 38', ' 38', ' 39', ' 39', ' 39', ' 39', ' 39'],
    ['France', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4', ' 4'],
    ['France', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3', ' 3'],
    ['France', ' 30096', ' 30109', ' 30108', ' 30123', ' 30150', ' 30150', ' 30150'],
    ['Netherlands', ' 15', ' 15', ' 15', ' 15', ' 15', ' 15', ' 16'],
    ['United Kingdom', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1', ' 1'],
]

# Group the lists based on country. This will give us a dict-of-lists-of-lists.
# Like this: grouped_lists{COUNTRY} = [ [...], [...], etc ]
grouped_lists = {}
for xs in raw_lists:
    # Grab country name and the rest of the values.
    c = xs[0]
    vals = xs[1:]
    assert len(vals) == 7
    # Convert the values to integers using a list comprehension.
    nums = [int(v.strip()) for v in vals]
    # Add the list of numbers to the country's list-of-lists.
    grouped_lists.setdefault(c, []).append(nums)

# Sum up the separate lists for each country.
country_totals = {}
for c, xss in grouped_lists.items():
    # Initialize the key for the country.
    country_totals[c] = []
    # Since xss is a list-of-lists for the current country, we can use zip() to
    # weave together the values based on their positions (or indexes). For
    # example, on the first iteration tup will be a tuple holding the first
    # elements from the separate lists. On second iteration, second elements. Etc.
    for tup in zip(*xss):
        country_totals[c].append(sum(tup))

# Take a look.
print(json.dumps(country_totals))

【讨论】:

  • 嘿,抱歉,我一直在尝试让您的代码与我的代码一起正常工作。最后它起作用了,所以我只想说谢谢,我接受了答案并给了它一个赞成票。谢谢!
【解决方案2】:

您可以使用itertools.groupby 获取分组的数字,并为您的密钥确定字符串是否为数字(我使用了str.isdigit)。

然后将它们转换为数字,

最后对结果进行逐元素求和(可以使用mapoperator.add 完成)。

这一切都可以在一行中完成。

from itertools import groupby
from operator import add

data = ['China', '8','7','2', 'China','2','34','18']

china = list(map(add, *(tuple(map(int, g)) for k, g in groupby(data, str.isdigit) if k)))

结果:

[10, 41, 20]

【讨论】:

  • 只是在一个单独的文件中运行你的答案我得到一个错误:` full = list(map(add, *(tuple(map(int, g)) for k, g in groupby(L, str.isdigit) if k))) TypeError: map() must have at least two arguments.` 可能会发生什么?(不过你的答案似乎很可靠)
  • 你确定你给它的数据和我一样吗?
  • 是的,我创建了一个新文件并复制了您的代码。我用的是python 3.8,你呢?
  • 我的意思是,您评论中的 L 在我的回答中看起来像 data
  • 不,我认为你不明白。我从字面上复制了你的代码。没有什么不同,只是相同的东西相同的变量,一切都是一样的。一个简单的复制和粘贴。我把它放在一个单独的文件中只是为了测试它,它没有工作。
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多