Ramesh Reddy
Ramesh Reddy

Reputation: 10662

python lists having chars and digits

if I have a list:

x=[1,'A',2,'B',3,'C',2,'A',1,'B']

here in the above list the digits and characters are related as A contains 1,B contains 2, C contains 3 and again A contains 2(total 3) ,B contains 1(total 3)

if I want to find what each character contains finally..how can I do it I did this- I found characters in the list x initially like y=['A','B','C'] then I used a loop to iterate x and whenever I find A in x I added the previous value based on index and so on...but its not working sometimes.

Upvotes: 0

Views: 309

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

You could do something like this, assuming you want a dictionary as output:

data = [1,'A',2,'B',3,'C',2,'A',1,'B']

result = {}
for number, letter in zip(data[::2], data[1::2]):
    result.setdefault(letter, []).append(number)

print(result)

Output

{'B': [2, 1], 'C': [3], 'A': [1, 2]}

If you want only the last contained number, you could use a dictionary comprehension (see the documentation here):

data = [1, 'A', 2, 'B', 3, 'C', 2, 'A', 1, 'B']
result = {letter: number for number, letter in zip(data[::2], data[1::2])}
print(result)

Output

{'B': 1, 'C': 3, 'A': 2}

Or if you want the sum of all elements, you can use a combination of both answer above:

data = [1,'A',2,'B',3,'C',2,'A',1,'B']

result = {}
for number, letter in zip(data[::2], data[1::2]):
    result.setdefault(letter, []).append(number)

result = { letter : sum(numbers) for letter, numbers in result.items()}
print(result)

Output

{'A': 3, 'B': 3, 'C': 3}

Further

  1. Documentation on setdefault
  2. Documentation on zip

Upvotes: 4

Related Questions