This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Closed 5 years ago.
How to create a dictionary from List when my list is like below
L1 = [1,2,3,4,5,6,7,8,9]
and I want the result as a dictionary like
d = {'1':[2,3], '4':[5,6], '7':[8,9]}
Is any idea, how to implement this?
L = [1,2,3,4,5,6,7,8,9]
n = 3
dict = {}
for i in range(0, len(L), n):
#this creates chunks of size n
sub_list = L[i:i+n]
dict[sub_list[0]] = sub_list[1:]
print(dict)
To get dictionary entries of size 2, choose n=3 in this example.
one-liner:
dict((L1[i*3], [L1[i*3+1], L1[i*3+2]]) for i in xrange(len(L1)/3))
Explanation:
xrange(len(L1)/3) returns a lazy range from 0 to 2: [0, 1, 2].
Further for each element i of a range it transforms to a tuple (k, [v1, v2]]). So the final range will be [(1, [2, 3]), (4, [5, 6]), (7, [8, 9])]. And finally we use a dict constructor from list of tuples where each element considered as a key-value pair.
Final result is {1: [2, 3], 4: [5, 6], 7: [8, 9]}. To convert keys from number to string we need to replace L1[i*3] to str(L1[i*3]).
Related
This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 6 months ago.
Given a nested list of integers, implement an iterator to flatten it. Each
element is either an integer, or a list -- whose elements may also be integers
or other lists. For example, if the input is [[1,1],2,[1,1]], then the output
is [1, 1, 2, 1, 1]. If the input is [1,[4,[6]]], then the output is [1, 4, 6].
Would anyone be able to advise me as to where the code below went wrong?
I am just starting out with python.
def eb34(list1):
flat_list = []
for i in range(len(list1)):
if type(list[i]) == list:
flat_list += flatten(list1[i])
else:
flat_list.append(list1[i])
return flat_list
You can use recursion:
def flatten(arg):
if not isinstance(arg, list): # if not list
return [arg]
return [x for sub in arg for x in flatten(sub)] # recurse and collect
print(flatten([[1,1],2,[1,1]])) # [1, 1, 2, 1, 1]
print(flatten([1,[4,[6]]])) # [1, 4, 6]
Or to make a generator,
def flatten(arg):
if not isinstance(arg, list): # if not list
yield arg
else:
for sub in arg:
yield from flatten(sub)
print(*flatten([[1,1],2,[1,1]])) # 1 1 2 1 1
print(*flatten([1,[4,[6]]])) # 1 4 6
I don't know from where you are calling flatten() in your code. I am giving you a solution with the other information you have given.
def eb34(list1):
flat_list = []
for i in list1:
if isinstance(i, list):
for j in eb34(i):
flat_list.append(j)
else:
flat_list.append(i)
return flat_list
You can recursively flatten it:
def flatten_recursively(lst_in):
lst_out = []
for i in lst_in:
if type(i) == list:
for j in flatten_recursively(i):
lst_out.append(j)
else:
lst_out.append(i)
return lst_out
Also check out this answer, although you might have to adjust it to Python 3+: https://stackoverflow.com/a/10824420/18189622
The easiest way to make a flat list from nested lists is to use the itertools module. The itertools module has a function called chain that takes a list of lists and returns a single list.
>>> import itertools
>>> nested_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flat_list = list(itertools.chain(*nested_lists))
>>> flat_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
This question already has answers here:
Sorting list based on values from another list
(20 answers)
Closed 3 years ago.
I need a function that turns a list like
[10,5,2,3,7]
to a list like
[4,2,0,1,3]
Basically a list [0,1,2,3,4...] but arranged in the order that the original list has, smallest to biggest.
I have no idea where to even start on a function like this. I have Python 3.5.2.
hiro protagonist's answer was close, but he indexed the wrong list.
>>> data = [10,5,2,3,7]
>>> sorted_list = sorted(data)
>>> [sorted_list.index(item) for item in data]
[4, 2, 0, 1, 3]
This wouldn't account for cases where you want to account for multiple occurrences and whatnot, but I'm not sure if that's required in your case.
Try this:
>>> d = [10, 5, 2, 3, 7]
>>> [sorted(d).index(i) for i in d]
[4, 2, 0, 1, 3]
This solution would work; however, there is probably a solution that is more space efficient. This solution does allow for repeat elements though.
l1 = [10, 5, 2, 3, 7] # Your list
l2 = sorted(l1) # Get the sorted version of our list.
# A dictionary containing each element and a list of the indices where they are found
element_indices = {}
for index, element in enumerate(l2):
if element not in element_indices:
element_indices[element] = [index] # Store the index for each element when it is sorted
else: # We have seen this element before
element_indices[element].append(index)
l2 = [element_indices[value].pop() for value in l1] # Change each element to its sorted equivalent index
print(l2) # [4, 2, 0, 1, 3]
This question already has answers here:
Transpose nested list in python
(4 answers)
Transpose list of lists
(14 answers)
Closed 5 years ago.
It should work like
input: list([[1,1,1],[2,2,2],[3,3,3]])
output: [[1,2,3], [1,2,3], [1,2,3]]
so far i have done this:
def list(m):
list2=[]
for i in range(0, len(m)):
list2.append([x[i] for x in m])
return(list2)
It's not working every time..
For example:
it's working for
input: list([[1,1,1],[2,2,2],[3,3,3]])
but not for
input: list([[1,3,5],[2,4,6]])
You would usually do that in Python using the zip function:
inp = list([[1,1,1],[2,2,2],[3,3,3]])
output = list(map(list, zip(*inp)))
print(output)
>>> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
The additional map call is to convert the elements returned by zip, that are tuples, into lists, but if you are okay with tuples you can just do:
inp = list([[1,1,1],[2,2,2],[3,3,3]])
output = list(zip(*inp))
print(output)
>>> [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
Also, the outer list is only necessary in Python 3, where zip returns a generator, but not in Python 2.
This question already has answers here:
Remove adjacent element in a list in python
(2 answers)
Closed 7 years ago.
I have a list like this: [1, 3, 4, 5, 1]
and I want to remove the first n elements, so for n = 3, I want to return that list, while removing it from the original list. So I'd have [1,3,4]
and my original list is now [5, 1].
What is the best way to do that in python?
In Python 2.7 this would look like the following. Simply extract a partial list and delete the unneeded part in the original version.
lst = [1, 3, 4, 5, 1]
new_lst = lst[:3]
del lst[:3]
print lst
print new_lst
If you want to mutate the original object, you can change it using [:]. For example:
>>> x = ['a','b','c','d','e']
>>> x[:], removed = x[3:], x[:3]
>>> x
['d', 'e']
>>> removed
['a', 'b', 'c']
This works because the terms on the right hand side, x[3:] and x[:3], are both evaluated before they're assigned to the targets on the left (x[:] and removed).
Something like this?
def pop_n(lst, n):
"""
Deletes the first *n* elements from *lst* and returns them.
"""
# validate inputs
# might want to use something other than isinstance()
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer, not {}"
.format(n))
# store the elements to return
ret = lst[:n]
# remove the elements from the original list
del lst[:n]
return ret
EDIT: Here's a demonstration with your example case.
>>> x = [1, 3, 4, 5, 1]
>>> pop_n(x, 3)
[1, 3, 4]
>>> x
[5, 1]
>>> original = [1, 3, 4, 5, 1]
>>> removed, original[:3] = original[:3], ()
>>> removed, original
([1, 3, 4], [5, 1])
This question already has answers here:
How to force a list to a fixed size?
(7 answers)
Closed 3 years ago.
I would like to remove the oldest-added (i.e. the first) elements of a list, such that this list never exceeds 100 elements.
I thought about:
L = [327983, 232382, 1, 2, 3, 4, 5, 6, 23]
if len(L) > 100:
for i in range(len(L)-100):
del L[0]
print L # [4, 5, 6, 23]
Is there a solution without iteration (or more generally: a nicer solution) for trimming the beginning of the list, so that it has <= 100 elements?
Sidenote: Isn't there something else than lists, for this purpose? i.e. a data structure that has a maximum size, and such that if more data comes, the oldest are deleted! (It makes me think about FIFO? Stack? Pipe?)
How about using collection.deque? If you specify maxlen, it will not store more than maxlen elements.
>>> from collections import deque
>>> q = deque([1, 2, 3], maxlen=3)
>>> q
deque([1, 2, 3], maxlen=3)
>>> q.append(4)
>>> q
deque([2, 3, 4], maxlen=3)
You can just assign a slice back to your list
L = L[-100:]