Home > Enterprise >  Print item of list and another item of list side by side
Print item of list and another item of list side by side

Time:09-28

Suppose I have two lists:

list1=[1, 2, 2, 12, 23]
list2=[2, 3, 5, 3, 4]

I want to arrange them side by side list1 and list2 using python so:

| list1 | list2 |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 2 | 5 |
| 12 | 3 |
| 23 | 4 |

but I want to remove the third row (2,5) and make it:

| list1 | list2 |
|---|---|
| 1 | 2 |
| 2 | 3,5 |
| 12 | 3 |
| 23 | 4 |

CodePudding user response:

You could zip the two lists together and append them to a dictionary. If one value of list 1 already exists as a key in the dictionary, you format the value as a string and append the next one to the same key. I just posted this since it might be easier to follow, however i really like the answer above from @buran.

list1 = [1, 2, 2, 12, 23]
list2 = [2, 3, 5, 3, 4]
combo_dict = {}

# zip both lists together and iterate over them
for key, val in zip(list1, list2):
    """if an item in list1 already exists in combo_dict, 
       format the respective overlapping value in list2 as a 
       string and append to the same key to the dict"""
    if key in combo_dict.keys():
        combo_dict[key] = ",".join([f"{combo_dict[key]}", f"{val}"])
    """if not, simply append the value of list 2 with the key of 
       list 1 to the dict (could also format this to a string)"""
    else:
        combo_dict[key] = val

# this is just for printing the dict to the console
no_out=[print(f"{key} {val}") for key, val in combo_dict.items()]

CodePudding user response:

Using itertools.groupby:

from itertools import groupby

list1=[1, 2, 2, 12, 23]
list2=[2, 3, 5, 3, 4]

for key, value in groupby(zip(list1, list2), key=lambda x: x[0]):
    print(f"{key} {','.join(str(y) for x, y in value)}")

or if you prefer using collections.defaultdict:

from collections import defaultdict

list1=[1,2,2,12,23]
list2=[2, 3, 5, 3, 4]

result = defaultdict(list)
for key, value in zip(list1, list2):
    result[key].append(value)

for key, value in result.items():
    print(f"{key} {','.join(map(str, value))}")

using only loops and built-in functions:

list1=[1,2,2,12,23]
list2=[2, 3, 5, 3, 4]

result={}
for key, value in zip(list1, list2):
    result.setdefault(key, []).append(value)

for key, value in result.items():
    print(f"{key} {','.join(map(str, value))}")

In all three cases the output is

1 2
2 3,5
12 3
23 4
  • Related