Lets say I have the following list:
StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']
And I want to generate the following result:
FinalList = [[1,8,0,9],[4,5,2,2],[4,6,7,2],[4,2,8,9]]
I am using the following code:
TempList = [d.split(',') for d in StringLists]
FinalList = list()
for alist in TempList:
FinalList.append([int(s) for s in alist])
The result is ok, but i was wondering if there is something more elegant. Any idea?
What about:
FinalList = [list(map(int, d.split(','))) for d in StringLists]
Note that if you are using Python 2, you do not have to cast the result:
FinalList = [map(int, d.split(',')) for d in StringLists]
One way to do it
>>> [[int(s) for s in string.split(',')] for string in StringLists]
[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]
You can use:
StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']
print map(lambda s: map(int, s.split(',')), StringLists)
Output:
[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]
How about this:
TempList = [map(int, d.split(',')) for d in StringLists]
Related
I have a list
a = [[1,2,3],[3,4,5]]
In every row at the end I want to insert values from a different list
b=[6,7]
I want the results to be
[[1,2,3,6],[3,4,5,7]]
I am using:
for i in range (0,len(a)):
for j in range (0,len(b)):
if j==0:
a[i].append(b[j])
m.append(a[i])
else:
a[i][3]=b[j]
m.append(a[i])
print m
But I am not getting the expected results. This gives me:
[[1, 2, 3, 7], [1, 2, 3, 7], [3, 4, 5, 7], [3, 4, 5, 7]]
Could someone help me out with the correct code snippet.
Here is a solution using zip:
result = [sublist_a + [el_b] for sublist_a, el_b in zip(a, b)]
which gives the expected output:
[[1, 2, 3, 6], [3, 4, 5, 7]]
Using zip
Ex:
a=[[1,2,3],[3,4,5]]
b=[6,7]
for i, j in zip(a,b):
i.append(j)
print(a)
Output:
[[1, 2, 3, 6], [3, 4, 5, 7]]
How would you combine sublists within a list by pairs?
For example with:
list1 = [[1,2,3],[4,5],[6],[7,8],[9,10]]
the result would be:
[[1,2,3,4,5],[6,7,8],[9,10]]
You could use zip_longest with a fill value (in case your list has an odd number of sublists) to zip an iterator over list1. Running a list comprehension over the zip generator object allows you to concatenate the consecutive pairs of lists:
>>> from itertools import zip_longest # izip_longest in Python 2.x
>>> x = iter(list1)
>>> [a+b for a, b in zip_longest(x, x, fillvalue=[])]
[[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
Try using a list comprehension (but be careful with the indexes!). It works for lists with an even or odd number of sublists:
list1 = [[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]
n = len(list1)
[list1[i] + (list1[i+1] if i+1 < n else []) for i in xrange(0, n, 2)]
=> [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]
length = len(list1)
new_list = [ list1[i]+list1[i+1] if i+1 < length
else [list1[i]] for i in range(0,length,2) ]
print(new_list)
>>> list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]
>>> list1
[[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]
Now we can do:
>>> test = [list1[0]+list1[1]]+[list1[2]+list1[3]]+list1[4]
>>> test
[[1, 2, 3, 4, 5], [6, 7, 8], 9, 10]
>>>
I am sure there is a better way, but this is the way I can think of!
list1 = [[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]
from itertools import islice, chain
print([list(chain.from_iterable(islice(list1, i, i + 2)))
for i in range(0, len(list1), 2)])
[[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
Or without islice:
print([list(chain.from_iterable(list1[i:i+2]))
for i in range(0, len(list1), 2)])
[[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
Use a simple loop:
list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]
newlist = []
for i in range(0, len(list1), 2):
newlist.append(list1[i] + list1[i+1])
if len(list1) % 2 > 0:
newlist.append(list1[-1])
print newlist
Here is (I hope) a correct solution:
def pair_up(ls):
new_list = []
every_other1 = ls[::2]
every_other2 = ls[1::2]
for i in range(len(every_other2)):
new_list.append(every_other1[i]+every_other2[i])
if len(ls) % 2 == 1:
new_list.append(ls[-1])
return new_list
Working on same list with removing n-ths[-1] odd sublists:
for i in range(len(l)/2):#here we go only to last even item
l[i]+=l[i+1]#adding odd sublist to even sublist
l.pop(i+1)#removing even sublist
Hi I was wondering how I could un-nest a nested nested list. I have:
list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
I would like to to look as follows:
new_list = [[1,2,3], [4,5,6], [7,8,9]]
How to do it?
>>> L = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
>>> [x[0] for x in L]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
For multiple nestings:
def unnesting(l):
_l = []
for e in l:
while isinstance(e[0], list):
e = e[0]
_l.append(e)
return _l
A test:
In [24]: l = [[[1,2,3]], [[[[4,5,6]]]], [[[7,8,9]]]]
In [25]: unnesting(l)
Out[25]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I found another solution that might be easier and quicker here and also mentioned here.
from itertools import chain
nested_list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
my_unnested_list = list(chain(*nested_list))
print(my_unnested_list)
which results in your desired output as:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I have the following problem. Having a list of integers, I want to split it, into a list of lists, whenever the step between two elements of the original input list is not 1.
For example: input = [0, 1, 3, 5, 6, 7], output = [[0, 1], [3], [5, 6, 7]]
I wrote the following function, but it's uggly as hell, and I was wondering if anyone of you guys would help me get a nicer solution. I tried to use itertools, but couldn't solve it.
Here's my solution:
def _get_parts(list_of_indices):
lv = list_of_indices
tuples = zip(lv[:-1], lv[1:])
split_values = []
for i in tuples:
if i[1] - i[0] != 1:
split_values.append(i[1])
string = '/'.join([str(i) for i in lv])
substrings = []
for i in split_values:
part = string.split(str(i))
substrings.append(part[0])
string = string.lstrip(part[0])
substrings.append(string)
result = []
for i in substrings:
i = i.rstrip('/')
result.append([int(n) for n in i.split('/')])
return result
Thanks a lot!
This works with any iterable
>>> from itertools import groupby, count
>>> inp = [0, 1, 3, 5, 6, 7]
>>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))]
[[0, 1], [3], [5, 6, 7]]
def _get_parts(i, step=1):
o = []
for x in i:
if o and o[-1] and x - step == o[-1][-1]:
o[-1].append(x)
else:
o.append([x])
return o
_get_parts([0, 1, 3, 5, 6, 7], step=1)
# [[0, 1], [3], [5, 6, 7]])
Here is a solution utilizing a for loop.
def splitbystep(alist):
newlist = [[alist[0]]]
for i in range(1,len(alist)):
if alist[i] - alist[i-1] == 1:
newlist[-1].append(alist[i])
else:
newlist.append([alist[i]])
return newlist
This is how I'd do it:
inp = [0, 1, 3, 5, 6, 7]
base = []
for item in inp:
if not base or item - base[-1][-1] != 1: # If base is empty (first item) or diff isn't 1
base.append([item]) # Append a new list containing just one item
else:
base[-1].append(item) # Otherwise, add current item to the last stored list in base
print base # => [[0, 1], [3], [5, 6, 7]]
This is the textbook use case for function split_when from module more_itertools:
import more_itertools
print(list(more_itertools.split_when([0, 1, 3, 5, 6, 7], lambda x,y: y-x != 1)))
# [[0, 1], [3], [5, 6, 7]]
Or, even more simple with more_itertools.consecutive_groups:
print([list(g) for g in more_itertools.consecutive_groups([0, 1, 3, 5, 6, 7])])
# [[0, 1], [3], [5, 6, 7]]
Suppose I have a python list l=[1,2,3,4,5]. I would like to find all x-element lists starting with elements that satisfy a function f(e), or the sublist going to the end of l if there aren't enough items. For instance, suppose f(e) is e%2==0, and x=3 I'd like to get [[2,3,4],[4,5]].
Is there an elegant or "pythonic" way to do this?
>>> f = lambda e: e % 2 == 0
>>> x = 3
>>> l = [1, 2, 3, 4, 5]
>>> def makeSublists(lst, length, f):
for i in range(len(lst)):
if f(lst[i]):
yield lst[i:i+length]
>>> list(makeSublists(l, x, f))
[[2, 3, 4], [4, 5]]
>>> list(makeSublists(list(range(10)), 5, f))
[[0, 1, 2, 3, 4], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8], [6, 7, 8, 9], [8, 9]]
Using a list comprehension:
>>> l = range(1,6)
>>> x = 3
>>> def f(e):
return e%2 == 0
>>> [l[i:i+x] for i, j in enumerate(l) if f(j)]
[[2, 3, 4], [4, 5]]