0

How to obtain a name and data of two different lists

Example: List=[“123 Kevin”, “122 Mark”] List2= [“123 Apple”, “123 Plane”, “122 Pizza” ] Output 123 Kevin Apple plane 122 mark pizza

19th May 2022, 3:07 PM
Kevin
2 ответов
+ 3
I would merge the two lists. You can use + to do it: a = [1,2,3] b = [4,5,6] c = a + b print(c) #[1,2,3,4,5,6]
19th May 2022, 3:25 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
- Create an empty dictionary first - Run a for loop on the combined list of the two - For each element do - Slice first 3 character of the element and check if that slice exists as key in dictionary - If it does, update dictionary item by adding a slice of the element (starting from 4th character) to the item value - Otherwise create a new dictionary item with 3 first characters slice as item key, and rest of the element (starting from 4th character) as the item value * You can also opt to split the element rather than using slicing, if you are sure that each splitted element will result only in two chunks. List1 = [ "123 Kevin", "122 Mark" ] List2 = [ "123 Apple", "123 Plane", "122 Pizza" ] mydict = {} for el in List1 + List2: dkey = el[ : 3 ] if dkey in mydict: mydict[ dkey ] += el[ 3 : ] else: mydict[ dkey ] = el[ 3 : ] for k, v in mydict.items(): print( f"{k} {v}")
20th May 2022, 11:16 AM
Ipang