Append to list from another list - python

i have list like
list = ['1,2,3,4,5', '6,7,8,9,10']
I have problem with "," in list, because '1,2,3,4,5' its string.
I want to have list2 = ['1','2','3','4'...]
How i can do this?

Should be something like that:
nums = []
for str in list:
nums = nums + [int(n) for n in str.split(',')]

You can loop through and split the strings up.
list = ['1,2,3,4,5', '6,7,8,9,10']
result = []
for s in list:
result += s.split(',')
print(result)

Split each value in the original by , and then keep appending them to a new list.
l = []
for x in ['1,2,3,4,5', '6,7,8,9,10']:
l.extend(y for y in x.split(','))
print(l)

Use itertools.chain.from_iterable with map:
from itertools import chain
lst = ['1,2,3,4,5', '6,7,8,9,10']
print(list(chain.from_iterable(map(lambda x: x.split(','), lst))))
# ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Note that you shouldn't use list name for variables as it's a built-in.

You can also use list comprehension
li = ['1,2,3,4,5', '6,7,8,9,10']
res = [c for s in li for c in s.split(',') ]
print(res)
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

list2 = []
list2+=(','.join(list).split(','))
','.join(list) produces a string of '1,2,3,4,5,6,7,8,9,10'
','.join(list).split(',') produces ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
join method is used to joined elements in a list by a delimiter. It returns a string in which the elements of sequence have been joined by ','.
split method is used to split a string into a list by a delimiter. It splits a string into an array of substrings.

# Without using loops
li = ['1,2,3,4,5', '6,7,8,9,10']
p = ",".join(li).split(",")
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Related

How to sort a list of integers that are stored as string in python [duplicate]

This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 2 years ago.
I tried to sort a list of string that are actually integers but i do not get the right sort value. How do i sort it in a way that it is sorted according to the integer value of string ?
a = ['10', '1', '3', '2', '5', '4']
print(sorted(a))
Output:
['1', '10', '2', '3', '4', '5']
Output wanted:
['1', '2', '3', '4', '5', '10']
We have to use the lambda as a key and make each string to int before the sorted function happens.
sorted(a,key=lambda i: int(i))
Output :
['1', '2', '3', '4', '5', '10']
More shorter way -> sorted(a,key=int). Thanks to #Mark for commenting.
So one of the ways to approach this problem is converting the list to a list integers by iterating through each element and converting them to integers and later sort it and again converting it to a list of strings again.
You could convert the strings to integers, sort them, and then convert back to strings. Example using list comprehensions:
sorted_a = [str(x) for x in sorted(int(y) for y in a)]
More verbose version:
int_a = [int(x) for x in a] # Convert all elements of a to ints
sorted_int_a = sorted(int_a) # Sort the int list
sorted_str_a = [str(x) for x in sorted_int_a] # Convert all elements of int list to str
print(sorted_str_a)
Note: #tedd's solution to this problem is the preferred solution to this problem, I would definitely recommend that over this.
Whenever you have a list of elements and you want to sort using some property of the elements, use key argument (see the docs).
Here's what it looks like:
>>> a = ['10', '1', '3', '2', '5', '4']
>>> print(sorted(a))
['1', '10', '2', '3', '4', '5']
>>> print(sorted(a, key=lambda el: int(el)))
['1', '2', '3', '4', '5', '10']

Appending temporary lists from loop ends up with multiple copies of the same list

I am trying to practice to make a method.
s = '132'
lis = list(s)
result = []
lisc = lis[:]
for item in lis:
for i in range(1,len(lis)):
lisc.remove(item)
lisc.insert(i,item)
print("lis : ", lisc)
result.append(lisc)
print(result)
The result is :
lis : ['3', '1', '2']
lis : ['3', '2', '1']
lis : ['2', '3', '1']
lis : ['2', '1', '3']
lis : ['1', '2', '3']
lis : ['1', '3', '2']
[['1', '3', '2'], ['1', '3', '2'], ['1', '3', '2'], ['1', '3', '2'], ['1', '3', '2'], ['1', '3', '2']]
I don't get why the result is appending the original lisc instead of the modified lisc in the loop.
I tried result.append(lisc[:]) and it works.
for item in lis:
for i in range(1,len(lis)):
lisc.remove(item)
lisc.insert(i,item)
print("lis : ", lisc)
result.append(lisc[:])
print(result)
Can anyone answer my question?
Thank you in advance.
In the first version of your code, you append the same list that it's being updated at every iteration. In the end, all the lisc you appended will be a reference to the same list
In the second version, you append a new copy of the modified list. Those copies are all different object

python slice set in list

i would like to slice a set within a list, but every time i do so, i get an empty list in return.
what i try to accomplish (maybe there is an easier way):
i got a list of sets
each set has 5 items
i would like to compare a new set against the list (if the set already exists in the list)
the first and the last item in the set is irrelevant for the comparison, so only the positions 2-4 are valid for the search of already existing sets
here is my code:
result_set = ['1', '2', '3', '4', '5']
result_matrix = []
result_matrix.append(result_set)
slicing the set is no problem:
print result_set[1:4]
['2', '3', '4']
print result_matrix[:][1:4]
[]
i would expect:
[['2', '3', '4']]
I think this is what you want to do:
>>> target_set = ['2', '3', '4']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
True
>>> target_set = ['1', '2', '3']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
False
Generalising and making that a function:
def is_set_in_matrix(target_set, matrix):
return any(True for l in matrix if list(target_set) == l[1:-1])
>>> result_matrix = [['1', '2', '3', '4', '5']]
>>> is_set_in_matrix(['1', '2', '3'], result_matrix)
False
>>> is_set_in_matrix(['2', '3', '4'], result_matrix)
True
# a quirk - it also works with strings...`
>>> s = '234'
>>> is_set_in_matrix(s, result_matrix)
True
Note that I have used l[1:-1] to ignore the first and last elements of the "set" in the comparison. This is more flexible should you ever need sets of different lengths.
>>> result_set = ['1', '2', '3', '4', '5']
>>> print result_set[1:4]
['2', '3', '4']
>>> result_matrix.append(result_set[1:4])
>>> result_matrix
[['2', '3', '4']]
Using result_matrix[:] returns the whole matrix as it is. You need to treat the result you want as a part of the array.
>>> result_matrix.append(result_set)
>>> result_matrix[:]
[['1', '2', '3', '4']]
>>> result_matrix[:][0]
['1', '2', '3', '4']
>>> result_matrix[0][1:4]
['2', '3', '4']
Also, as pointed out by falsetru:
>>> result_matrix.extend(result_set)
>>> result_matrix
['1', '2', '3', '4']
>>> result_matrix[1:4]
['2', '3', '4']

List circulation in Python for Project Euler 37

So, I was doing Project Euler 37
I need to circulate a list
input: 2345 # converted to list inside function
expected output: [[3,4,5,2],[4,5,2,3],[5,2,3,4],[2,3,4,5]]
Here is my function for that
def circulate(n): #2345
lst=list(str(n)) #[2,3,4,5]
res=[]
for i in range(len(lst)):
temp=lst.pop(0)
lst.append(temp)
print lst #print expected list
res.append(lst) #but doesn't append as expected
return res
print circulate(2345)
My output is:
['3', '4', '5', '2']
['4', '5', '2', '3']
['5', '2', '3', '4']
['2', '3', '4', '5']
[['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']]
The function prints lst correct every time, but doesn't append as expected.
What I am doing wrong?
You need to append copies of your list to res:
res.append(lst[:])
You were appending a reference to the list being altered instead; all references reflect the changes made to the one object.
You may want to look at collections.deque() instead; this double-ended list object supports efficient rotation with a .rotate() method:
from collections import deque
def circulate(n):
lst = deque(str(n))
res = []
for i in range(len(lst)):
lst.rotate(1)
res.append(list(lst))
return res

Insert gives me an empty list? What is going on here?

>>> numlist = ['0', '1', '2', '3', '4', '5', '6']
>>> numlist = numlist.insert(0, '-1')
>>> numlist
>>> print numlist
None
>>>
I don't get it - I am trying to append to the first position of the list, and it is giving me a NoneType?
list.insert modifies the list in-place and returns None. Use it like this instead:
>>> numlist = ['0', '1', '2', '3', '4', '5', '6']
>>> numlist.insert(0, '-1')
>>> numlist
['-1', '1', '2', '3', '4', '5', '6']
Also, is there any particular reason you are using quoted numbers?
list.insert returns None, not a list.
Try numlist.insert(0, '-1') without the assignment.
Just use
numlist.insert(0, '-1')
list.insert will return a None

Categories