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']
Related
I've written a script to make the length of all the lists at least 3 no matter what are their individual length at this moment.
Currently the list of lists I have:
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
I've tried with:
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
for item in item_list:
if len(item)<3:
item.extend([""])
elif len(item)<2:
item.extend([""]*2)
print(item_list)
Output I'm getting:
[['1', '2', ''], ['3', '4', '5'], ['2', '4', '5'], ['1', '']]
Desired output:
[['1', '2', ''], ['3', '4', '5'], ['2', '4', '5'], ['1', '','']]
How can I make the length of all the lists at least 3 irrespective of their current length?
for item in item_list:
item += ['']*(3-len(item))
You have written the order in reverse
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
for item in item_list:
if len(item)<2:
item.extend([""]*2)
elif len(item)<3:
item.extend([""])
print(item_list)
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']
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
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
>>> 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