List Comprehension - Conditional [duplicate] - python

This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 22 days ago.
For these 2 lists:
A=['3.40', '4.00', '151.00', '8.00', '81.00', '23.00', '17.00', '8.50', '5.00', '151.00', 'SCR', 'SCR', '13.00']
B=['11', '5', '2', '4', '6', '9', '7', '8', '10', '1', '12', '10', '3']
The desired output is:
C=['11', '5', '2', '4', '6', '9', '7', '8', '10', '1', '3']
So - list 'A' and list 'B' are the same length. List 'C' is the same as list 'B' - but does not have the values where 'SCR' exists in list 'A'.
My attempt at this is:
C = [x for x in B if x in A!='SCR']
Thankyou

just zip them together:
C = [b for a,b in zip(A,B) if a != 'SCR']

Based on what I think you're trying to accomplish, I think you would need this:
C = [B[x] for x in range(len(B)) if A[x] != 'SCR']

This is straightforward using the built-in enumerate function:
[x for (idx, x) in enumerate(B) if A[idx] == 'SCR']

Related

Merging every 2 elements of a list in Python [duplicate]

This question already has answers here:
list comprehension joining every two elements together in a list
(4 answers)
Joining pairs of elements of a list [duplicate]
(7 answers)
Closed 9 months ago.
So let's say I have a list as follows:
Li = ['1', '2', '3', '4', '5', '6', '7', '8']
I want to have a list modification to have this:
Li = ['12', '34', '56', '78']
Is it possible to merge every 2 elements of a list together?
>>> Li = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> [''.join(Li[i:i+2]) for i in range(0, len(Li), 2)]
['12', '34', '56', '78']
And if you prefer functional python:
list(map(lambda x: x[0]+x[1], zip(*[iter(Li)] * 2)))
You could use map on striding subsets of the list that step by 2 and are offset by 1:
list(map(str.__add__,Li[::2],Li[1::2]+[""]))
['12', '34', '56', '78']
Note: The +[""] is there to cover cases where the list has an odd number of elements

how to convert parts of a large list and divide up into smaller, simpler lists? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a large list an example of this list would be:
list = ['1', '2', '3', 'x', '4', '5', '6', 'x', '7', '8', '9', 'x']
I am struggling to create separate lists from this total list value separated by the value 'x'.
So for example, I need the above list to be converted to this:
list1 = ['1', '2', '3',]
list2 = ['4', '5', '6',]
list3 = ['7', '8', '9',]
Thank you for any help that you can give.
You can use a temporary list to store the values between 'x' and then use a condition to find 'x' and load the list to your new set of list
my_list = ['1', '2', '3', 'x', '4', '5', '6', 'x', '7', '8', '9', 'x']
new_list = []
temp_list = []
for value in my_list :
if value != 'x':
temp_list.append(value)
else:
new_list.append(temp_list)
temp_list = []
for sub_list in new_list:
print(sub_list)
Results:
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']
Just for fun here is a version using all kinds of fun methods but IMO harder to follow.
test_list = ['1', '2', '3', 'x', '4', '5', '6', 'x', '7', '8', '9', 'x']
idx_list = [idx + 1 for idx, val in enumerate(test_list) if val == 'x']
res = [test_list[i: j] for i, j in zip([0] + idx_list, idx_list +
([len(test_list)] if idx_list[-1] != len(test_list) else []))]
print(res)
Her'e a slightly more general version using groupby that will work for all iterables:
from itertools import groupby
def split(iterable, delimiter):
return [list(v) for k, v in groupby(iterable, delimiter.__eq__) if not k]
l = ['1', '2', '3', 'x', '4', '5', '6', 'x', '7', '8', '9', 'x']
print(split(l, 'x'))
# [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
You can do this very efficiently by cleverly using strings. I convert the list to a string, so I can use the split function which splits it in sublists based on a part of the string. I than convert those back to lists and ignore the last empty one.
l = ['1', '2', '3', 'x', '4', '5', '6', 'x', '7', '8', '9', 'x']
s = "".join(l)
list1,list2,list3 = [list(substring) for substring in s.split('x')][:-1] #To skip the empty list from the trailing 'x'

Python 3.6 - reading the the values of rows from two lists after a conditional statement

Hi here is my code that looks for values that repeat 3 or more times in list a:
a = ['1','1','1','2','2','3']
b = ['4','5','1','7','8','4']
d = [item for item in a if a.count(item) >= 3]
print(d)
# ['1', '1', '1']
So my question is how can I also read the corresponding values in list b. Also list a and b are always the same size. My desired output should be:
output: [['1', '1', '1'], ['4', '5', '1']]
thank you!
You can solve this using zip:
>>> list(zip(*[(ai, bi) for ai, bi in zip(a, b) if a.count(ai) >= 3]))
[('1', '1', '1'), ('4', '5', '1')]
Just use enumerate:
d = [(item,c[1][i]) for i,item in enumerate(c[0]) if c[0].count(item) >= 3]
Then you can zip them together
d = zip(*d)
You can use itertools.compress() like below:
import itertools
a = ['1', '1', '6', '2', '1', '3']
b = ['4', '5', '1', '7', '8', '4']
a_items = [item for item in a if a.count(item) >= 3]
b_items = list(itertools.compress(b, (i in set(a_items) for i in a)))
res = [a_items, b_items]
Output:
>>> res
[['1', '1', '1'], ['4', '5', '8']]

How to quicksort a nested list. [duplicate]

This question already has answers here:
Sorting a nested list by a certain element without the sorting function.
(3 answers)
Closed 5 years ago.
I'm not sure how to implement the quicksort algorithm into a nested list. If I have a list like this:
L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]
and I want to order it based on the last number in each sublist.
Output:
final = [['Henry', '1', '5'], ['James', '1', '2'], ['Alan', '1', '1']]
I find an algorithm implementation from this question Quicksort with Python. And just redefine the comparison funciton:
L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]
less_than = lambda x, y: x[2] < y[2]
more_than = lambda x, y: x[2] >= y[2]
def qsort(arr):
if len(arr) <= 1:
return arr
else:
return qsort([x for x in arr[1:] if less_than(x, arr[0])]) + [arr[0]] + qsort([x for x in arr[1:] if more_than(x, arr[0])])
print(qsort(L))
Output:
[['Alan', '1', '1'], ['James', '1', '2'], ['Henry', '1', '5']]
Hope this helps.

Order of python generator expression

I have an example where the iteration order of a python generator expression seems to be different from the analogous list comprehension and generator function.
For example, the code
n = 10
d = {i : str(i) for i in range(n)}
for i in d:
print d[i],
print
def func_gen(d):
for i in range(n):
yield d[i]
print(list(func_gen(d)))
g = [d[i] for i in range(n)]
print(g)
g = {d[i] for i in range(n)}
print(list(g))
has the output
0 1 2 3 4 5 6 7 8 9
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '0', '3', '2', '5', '4', '7', '6', '9', '8']
I would expect the generator expression to produce an ordered output like it does with the list comprehension. Is there something about generator expressions that
says the order isn't guaranteed?
Why is the order for the generator expression different from the others, even though the constructs are almost identical? It isn't even the same order as iterating through the dictionary, so it doesn't seem like
it's deferring to that.
I'm seeing the same behavior in Python 2 and 3.
Dicts aren't ordered. You can't rely on their items to come back in any particular order, even between function calls.

Categories

Resources