Convert normal list to specific nested list [duplicate] - python

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 8 years ago.
I have a list in python that looks like that: [a,b,c,d,e,f,g,h,i]. I would like to convert this list to a list of lists (nested list). The second level of lists should contain four elements maximal. Therefore, the new list should look like that:
[
[a,b,c,d],
[e,f,g,h],
[i],
]
Is there a pythonic way to do this? I will have to do this several times so I would be pleased if anybody knows a way of doing this without using hundreds of indexes.

You can use a list comprehension, xrange, and Explain Python's slice notation:
>>> lst = ['a', 'b', 'c', 'd', 'e',' f', 'g',' h', 'i']
>>> n = 4 # Size of sublists
>>> [lst[x:x+n] for x in xrange(0, len(lst), n)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i']]
>>>

Related

How to print a jagged array vertically? [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 3 years ago.
I have an array like this:
arr = [['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j']]
How to get the output like this?
str = aei bfj cg dh
So basically, how to print a jagged array vertically?
from itertools import zip_longest
for row in zip_longest(*arr, fillvalue=''):
print(' '.join(row))
You can use itertools.zip_longest to stride column-wise, and then filter out when None is encountered. Then pass that as a generator expression through str.join to create a single space-delimited string.
>>> import itertools
>>> ' '.join(''.join(filter(None, i)) for i in itertools.zip_longest(*arr))
'aei bfj cg dh'

How to insert elements in a nested List in Python? [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 4 years ago.
I do not have much experience in Python.
All I want to do is to insert elements in nested lists.I have two lists which seems to be similar but their behaviour is completely different.
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
When I output print these two lists both give same output:
[['a', 'b'], ['a', 'b'], ['a', 'b']]
But when I try to insert elements in nested lists both do that in a different way. Below is the code for inserting elements in nested list.
list1 = [['a','b']] * 3
for item in list1:
item.append("Hello")
print (list1)
This outputs
[['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello']]
While when I define list in the following way it does exactly what I want.
list2 = [['a','b'],['a','b'],['a','b']]
for item in list2:
item.append("Hello")
print (list2)
This gives following output:
[['a', 'b', 'Hello'], ['a', 'b', 'Hello'], ['a', 'b', 'Hello']].
Why are these two behaving differently?
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
Screenshot of Program output
list1 = [['a', 'b']] * 3
This creates a list of lists, as you know. However, the nested lists are actually all references to the same list object.
So when you iterate over list1 with
for item in list1:
item refers to the same list object on each iteration. So you repeated append to the same list.
On the other hand, list2 in your example code is explicitly assigned a list with three different lists. Those lists happen to have the same elements, but they are distinct lists.
When you use the * operator here, you are saying "I want 3 of these".
So you're getting 3 references to the same ['a', 'b']. In your case, you're adding 'Hello' to that same ['a', 'b'] reference.
List of lists changes reflected across sublists unexpectedly
If you want to make 3 separate references, try using list comprehension:
>>> x = [['a', 'b'] for i in range(0, 3)]
>>> x
[['a', 'b'], ['a', 'b'], ['a', 'b']]
>>> x[0].append('Hello')
>>> x
[['a', 'b', 'Hello'], ['a', 'b'], ['a', 'b']]

How to copy list of lists from python without last elements from each list [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 5 months ago.
How can I copy list of lists and delete last element from each in one step ? I can do something like this, but would like to learn to do it in one step:
test2 = [["A","A","C"],
["C","A"],
["A","B","C","A"]]
import copy
test3 = copy.deepcopy(test2)
for item in test3:
del item[-1]
In one step, you'll want to use a list comprehension. Assuming your lists are two dimensional only and the sublists composed of scalars, you can use the slicing syntax to create a copy.
>>> [x[:-1] for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]
If your sublists contain mutable/custom objects, call copy.deepcopy inside the expression.
>>> [copy.deepcopy(x[:-1]) for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]

zip the values from a dictionary [duplicate]

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.

Python list in list [duplicate]

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 10 years ago.
I want convert list as follow:
list=[['a','b','c','d'],'e','f']
to
list['a','b','c','d','e','f']
how could I do this....Helples..
Check out itertools.chain, I think it's exactly what you need: http://docs.python.org/2/library/itertools.html#itertools.chain
>>> import itertools as it
>>> li = [['e', 'f', 'g'], 'a', 'b']
>>> list(it.chain.from_iterable(li))
['e', 'f', 'g', 'a', 'b']
This is pretty much the example from the documentation of that function, which is always a good place to start...

Categories

Resources