This question already has an answer here:
zip two values from the dictionary in Python
(1 answer)
Closed 6 years ago.
I have a dictionary in python 2.7 that has the following structure:
x = {
'1': ['a', 'b', 'c'],
'2': ['d', 'e', 'f']
}
The length of the value list is always the same and I would like to basically zip the value lists with corresponding values. So, in this case it will create three new lists as:
[['a', 'd'], ['b', 'e'], ['c', 'f']]
I know I can write an awful looking loop to do this but I was wondering if there is a more pythonic way to do this. I need to preserve the order.
You can do the following:
zip(*x.values())
Explanation:
x.values() returns [['a', 'b', 'c'], ['d', 'e', 'f']] (order may change so you might need to sort x first.)
zip([a, b], [c, d]) returns [[a, c], [b, d]]
To expand x.values() into arguments to zip, prepend * to it.
This is single line solves the problem but is likely worse looking than your loop. It loops over the sorted keys and produces a list to pass to zip and then maps over the result converting the tuples into lists.
>>> x = {'1': ['a', 'b', 'c'], '2': ['d', 'e', 'f']}
>>> map(list, zip(*[x[k] for k in sorted(x)]))
[['a', 'd'], ['b', 'e'], ['c', 'f']]
res = list(zip(x['1'], x['2']))
res = list(map(list, res))
An explanation:
zip(x['1'], x['2'])
Creates a zip object that links up your pairs.
res = list(zip(x['1'], x['2']))
That zip object now become a list of tuples.
list(map(list, res))
For each element in res (each tuple), change the data structure from tuple to list, as you requested in your desired output above (map the list data type onto all elements in res). Then, convert that map object into a list to arrive at the final, desired result.
Related
Im trying to join the letters as a string that's inside the list which is also inside the list. So for example, it looks like this [['a', 'b', 'c'], ['d', 'e', 'f']] however I want the result to look like 'ad be cf' which is basically taking the element that lies in the same position in the list. I know how to join the elements into a list that can look like 'abcdef', however, i don't know which I could add in order to return a string that looks like above.
Any advice would be thankful!
string = ''
new_grid = []
for a in grid:
for b in a:
string += b
return string
When you want to transpose lists into columns, you typically reach for zip(). For example:
l = [['a', 'b', 'c'], ['d', 'e', 'f']]
# make a list of columns
substrings = ["".join(sub) for sub in zip(*l)]
#['ad', 'be', 'cf']
print(" ".join(substrings))
# alternatively print(*substrings, sep=" ")
# ad be cf
This works:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = [list(pair) for pair in zip(my_list[0], my_list[1])]
for i in range(3):
string = ''.join(sorted_list[i])
print(string, end=" ")
First, we are pairing each individual list to its corresponding value using [zip][1], then we are joining it into a string, and printing it out.
This solution may not be the most efficient, but it's simple to understand.
Another quick solution without zip could look like this:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = list(map(lambda a, b: a + b, my_list[0], my_list[1]))
print(" ".join(sorted_list))
I have a dictionary of the form
{'D': ['A', 'B'], 'C': ['a'], 'B': ['b'], 'A': ['a'], 'S': ['C', 'D']}
and I might have as an input two lists i.e., ['A', 'C'] and ['B']. I want to take all combinations of the elements of those lists, here ['A' , 'B'], ['C', 'B'] and see if they are in my original dictionary and if yes return the keys where they where found.
I have created the two function below in order to do so
def func1(r1, r2):
return [[func2([outer, inner]) for inner in r2] for outer in r1]
def func2(r):
return [key for key, val in my_dictionary.items() if r in val]
so I might call them as func1(list1, list2) and I would expect here to get D back since it contains the list ['A', 'B'], what I get back are empty lists though.
What have I messed up in the functions above?
Your problem is the statement ... if r in val. It should probably be ... if r == val. In your case, the value val will be something like ['A', 'B'], and so will r, sometimes.
in checks if an element of val is r, which will obviously never be true. == compares all the elements in the two lists, which is what you want.
I have a list
a = ['a', 'b', 'c']
And I want to create a function Delete where it would print to a new list the lists['a', 'b'], ['b', 'c'] and ['a', 'c'].
My main goal here is designing a function that would return a set of lists consisting of the main list without an element of it.
What you want is all combinations of length n-1 where n is the length of your list.
>>> from itertools import combinations
>>> a = ['a', 'b', 'c']
>>> map(list, combinations(a, len(a)-1))
[['a', 'b'], ['a', 'c'], ['b', 'c']]
This will give you a list of lists.
Note that a set of lists which you requested is not possible because lists are not hashable.
I have a list of lists in python looking like this:
[['a', 'b'], ['c', 'd']]
I want to come up with a string like this:
a,b;c,d
So the lists should be separated with a ; and the values of the same list should be separated with a ,
So far I tried ','.join([y for x in test for y in x]) which returns a,b,c,d. Not quite there, yet, as you can see.
";".join([','.join(x) for x in a])
>>> ';'.join(','.join(x) for x in [['a', 'b'], ['c', 'd']])
'a,b;c,d'
To do it functionally you could use map:
l = [['a', 'b'], ['c', 'd']]
print(";".join(map(".".join, l)))
a.b;c.d
To remove duplicates in list of lists (named 'povijest'), I used:
povijest=[ list(set(x)) for x in povijest ]
But I makes some structure problem when printed because its not sorted.
Whats the syntax when sorting lists in list of lists?
This will sort by the first element in each list
povijest= sorted([list(set(x)) for x in povijest ])
This will sort each sub-list, then sort the whole thing by the first element
povijest = sorted([sorted(i) for i in provijest])
Input
proviject = [['a','c','b'],['z','y','x'],['e','a']]
Result
[['a', 'b', 'c'], ['a', 'e'], ['x', 'y', 'z']]