user13645394
user13645394

Reputation:

How to add elements in one list to another?

This may not a be question well received by the SO community. I am a 12 year old beginner Python coder and I am working on this project to gather Corona stats across multiple websites and GitHub posts. Then I would turn that into a graph. Some lists that have been created will have been generated by one country but in different provinces. So what I need to do is add each element in a list to another element in a list so that I can have only one list of the country. I have appended two or more list to one list called full and formatted it a bit and it looks a bit like this:

['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']

My Goal


So I need to add 8 to two for example and put that into a list:

An illustrative picture

Now that's simple:

list1 = full[1]+full[3]

But what if I needed to add multiple elements in a list to each other and the amount of lists in full(my list) where different every time(this would happened because China could have 8 provinces so I created 8 list while India has 50 provinces so I create 50 list).

Result


So here is what I would like to get but can't figure out.
['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']

Here is my code:

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()

(There is more but those files don't matter for my problem. Also it reads from a file that includes all the countries with more than more province. It is a bit too much to paste so I have a curl below) curl- O'https://raw.githubusercontent.com/BuddyBob/Py_Programs/master/Hackathon/Deaths/similar.txt' Or just use the link. Any help would be much appreciated

Here is a couple of lines from 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']

Upvotes: 2

Views: 459

Answers (2)

FMc
FMc

Reputation: 42421

Here's an illustration of one way to group and sum the data. There are definitely shorter and fancier ways to do this sort of thing, but this example breaks the steps down.

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))

Upvotes: 1

Jab
Jab

Reputation: 27515

You can use itertools.groupby to get the grouped numbers, and for your key just determine if the string is a number (I used str.isdigit).

Then convert them to numbers,

Finally perform an element-wise sum to the result (which can be done using map and operator.add).

This can all be done in one line.

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)))

Result:

[10, 41, 20]

Upvotes: 0

Related Questions