This is a way of appending to a list through for loop:
lst = []
for i in range(5):
lst.append(i)
Though the below may look nicer and better:
lst = [i for i in range(5)]
I was trying to write the below code same as the second format, but I keep getting error. can anyone help?
filtered_list = []
for childList in source_list:
filtered_childList = remove_emptyElements(childList)
if filtered_childList:
filtered_list.append(filtered_childList)
Try this code:
# one liner as you asked:
filtered_list = [remove_emptyElements(l) for l in source_list if remove_emptyElements(l)]
# but I think that this will be better:
filtered_list = (remove_emptyElements(l) for l in source_list)
filtered_list = [l for l in filtered_list if l]
Update:
To solve your issue from the comments you can use this code snippet:
sequences_result = []
for sequence in sequences:
for itemset in sequence:
itemset_result = []
for item in itemset.split(","):
itemset_result.append(item.strip())
sequences_result.append(itemset_result)
print(sequences_result)
Related
I have the list_of_lists and I need to get the string that contains 'height' in the sublists and if there is no height at all I need to get 'nvt' for the whole sublist.
I have tried the following:
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
_lists = []
for list in list_of_lists:
list1 = []
for st in list:
if ("height" ) in st:
list1.append(st)
else:
list1.append('nvt')
_lists.append(list1)
OUT = _lists
the result I need to have is :
_lists = ['nvt', 'height=4']
what I'm getting is:
_lists = [['nvt','nvt'],['nvt','nvt','height=4']]
This is a good case for implementing a for/else construct as follows:
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
result = []
for e in list_of_lists:
for ss in e:
if ss.startswith('height'):
result.append(ss)
break
else:
result.append('nvt')
print(result)
Output:
['nvt', 'height=4']
Note:
This could probably be done with a list comprehension but I think this is more obvious and probably has no significant difference in terms of performance
This should work, you can assign height variable to first value in the sublist where s.startswith("height") is True, and if nothing matches this filter, you can assign height to 'nvt'.
_lists = []
for sublist in list_of_lists:
height = next(filter(lambda s: s.startswith("height"), sublist), 'nvt')
_lists.append(height)
And if you wish to be crazy, you can use list comprehension to reduce the code to the:
_lists = [next(filter(lambda s: s.startswith("height"), sublist), 'nvt') for sublist in list_of_lists]
Try this (Python 3.x):
import re
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
_lists = []
r = re.compile("height=")
for li in list_of_lists:
match = list(filter(r.match, li))
if len(match) > 0:
_lists.extend(match)
else:
_lists.append('nvt')
OUT = _lists
print(OUT)
I'm trying to learn how I can convert Python list comprehensions to a normal for-loop.
I have been trying to understand it from the pages on the net, however when I'm trying myself, I can't seem to get it to work.
What I am trying to convert is the following:
1:
n, m = [int(i) for i in inp_lst[0].split()]
and this one (which is a little bit harder):
2:
lst = [[int(x) for x in lst] for lst in nested[1:]]
However, I am having no luck with it.
What I have tried:
1:
n = []
for i in inp_lst[0].split():
n.append(int(i))
print(n)
If I can get some help, I will really appreciate it :D
Generally speaking, a list comprehension like:
a = [b(c) for c in d]
Can be written using a for loop as:
a = []
for c in d:
a.append(b(c))
Something like:
a, b = [c(d) for d in e]
Might be generalized to:
temp = []
for d in e:
temp.append(c(d))
a, b = temp
Something like:
lst = [[int(x) for x in lst] for lst in nested[1:]]
Is no different.
lst = []
for inner_lst in nested[1:]:
lst.append([int(x) for x in inner_lst])
If we expand that inner list comprehension:
lst = []
for inner_lst in nested[1:]:
temp = []
for x in inner_lst:
temp.append(int(x))
lst.append(temp)
I need to get the value(the right hand value after the colon) in this list
list = [apple:tuesday, banana:wednesday, guava:thursday]
first your list will be like
list1=["apple:tuesday", "banana:wednesday", "guava:thursday"]
k=0
for i in list1:
x=i.split(":")
print(x)
list1[k]=x[1]
k+=1
print(list1)
i hope this is what you were trying to do
you can do this by list comprehension.it's easy and fast
l = ["apple:tuesday", "banana:wednesday", "guava:thursday"]
new_l = [item.split(":")[1] for item in l]
list comprehension work like this
l = [i for i in range(5)]
# l = [0,1,2,3,4]
I am really new to Python and I am having a issue figuring out the problem below.
I have a list like:
my_list = ['testOne:100', 'testTwo:88', 'testThree:76', 'testOne:78', 'testTwo:88', 'testOne:73', 'testTwo:66', 'testThree:90']
And I want to group the elements based on the occurrence of elements that start with 'testOne'.
Expected Result:
new_list=[['testOne:100', 'testTwo:88', 'testThree:76'], ['testOne:78', 'testTwo:88'], ['testOne:73', 'testTwo:66', 'testThree:90']]
Just start a new list at every testOne.
>>> new_list = []
>>> for item in my_list:
if item.startswith('testOne:'):
new_list.append([])
new_list[-1].append(item)
>>> new_list
[['testOne:100', 'testTwo:88', 'testThree:76'], ['testOne:78', 'testTwo:88'], ['testOne:73', 'testTwo:66', 'testThree:90']]
Not a cool one-liner, but this works also with more general labels:
result = [[]]
seen = set()
for entry in my_list:
test, val = entry.split(":")
if test in seen:
result.append([entry])
seen = {test}
else:
result[-1].append(entry)
seen.add(test)
Here, we are keeping track of the test labels we've already seen in a set and starting a new list whenever we encounter a label we've already seen in the same list.
Alternatively, assuming the lists always start with testOne, you could just start a new list whenever the label is testOne:
result = []
for entry in my_list:
test, val = entry.split(":")
if test == "testOne":
result.append([entry])
else:
result[-1].append(entry)
It'd be nice to have an easy one liner, but I think it'd end up looking a bit too complicated if I tried that. Here's what I came up with:
# Create a list of the starting indices:
ind = [i for i, e in enumerate(my_list) if e.split(':')[0] == 'testOne']
# Create a list of slices using pairs of indices:
new_list = [my_list[i:j] for (i, j) in zip(ind, ind[1:] + [None])]
Not very sophisticated but it works:
my_list = ['testOne:100', 'testTwo:88', 'testThree:76', 'testOne:78', 'testTwo:88', 'testOne:73', 'testTwo:66', 'testThree:90']
splitting_word = 'testOne'
new_list = list()
partial_list = list()
for item in my_list:
if item.startswith(splitting_word) and partial_list:
new_list.append(partial_list)
partial_list = list()
partial_list.append(item)
new_list.append(partial_list)
joining the list into a string with delimiter |
step1="|".join(my_list)
splitting the listing based on 'testOne'
step2=step1.split("testOne")
appending "testOne" to the list elements to get the result
new_list=[[i for i in str('testOne'+i).split("|") if len(i)>0] for i in step2[1:]]
I would like to loop a list and remove element if it meets the requirement. At the same time, I would transform the removed element and add the transformation result to another list.
Right now, I have implemented above logic by following code:
delete_set = set([])
for item in my_list:
if meet_requirement(item):
another_list.append = transform(item)
delete_set.add(item)
my_list = filter(lambda x:x not in delete_set, my_list)
The code is not so straight-forward, is there a better way to implement the logic?
You could do this with comprehensions only.
delete_set = set(I for I in my_list if meet_requirement(I))
another_list.extend(transform(I) for I in delete_set)
# or extend(transform(I) for I in my_list if I in delete_set), if duplicates/order matter
my_list = [I for I in my_list if I not in delete_set]
Not sure about pythonic, but if python had a partition function similar to haskell (or you could write a simple one yourself), the code wouldn't need to iterate over the original list twice (as in Cat Plus' solution).
I would use something like the following:
new_my_list, deleted_list = partition(my_list, meet_requirement)
deleted_list = [transform(e) for e in deleted_list]
you could do this
for i in reversed(xrange(len(my_list))):
if meet_requirement(my_list[i]):
another_list.append(transform(my_list.pop(i)))
then you might or might not want to reverse another_list (or you can use a deque and appendleft)
You could do this to avoid the set:
def part(items, others):
for item in items:
if meet_requirement(item):
others.append(item)
else:
yield item
mylist[:] = part(mylist, another_list)
>>> another_list = []
>>> new_list = []
>>>
>>> for item in my_list:
... (another_list if meet_requirement(item) else new_list).append(item)
...
>>> another_list = map(transform, another_list)
>>> my_list = new_list
zipped = zip(*[(item, transform(item)) for item in my_list \
if meet_requirement(item)])
another_list = zipped[1]
my_list = [item for item in my_list if item not in zipped[0]]
I needed something similar the other day:
def partition(pred, iterable):
result = ([], [])
for each in iterable:
result[pred(each)].append(each)
return result
xs = some_list
ys, xs[:] = partition(meet_some_requirement, xs)
ys = map(do_some_transformation, ys)
Or this one-pass variation:
def partition_and_transform(pred, iterable, *transform):
result = ([], [])
for each in iterable:
v = pred(each)
result[v].append(transform[v](each))
return result
ys, xs[:] = partition_and_transform(meet_some_reqirement, xs, do_some_transformation, lambda x:x)