It is allowed the use of a comprehension list on a "list of lists"?
I would like to extract a list from a nested list.
I did try this:
def main():
a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
board = [a,b,c]
y = [x for x in board[1][i] if i in range(0,3)]
print y
but I get "NameError: name 'i' is not defined".
I'm using the wrong syntax or nested list cannot be used like this?
Thanks a lot!
Nesting loops in list comprehensions work the same way as nesting regular for loops, one inside the other:
y = [x for i in range(3) for x in board[1][i]]
but in this case, just selecting board[1][:] would be easier and give you the same result; a copy of the middle row.
If you need to apply an expression to each column in that row, then just loop over board[1] directly:
y = [foobar(c) for c in board[1]]
Related
I have one of problem statement
List =[[[1,2],[3,4]]]
And i want 1st index from both nested list in list a and 2nd index from both nested list in list b using for loop and if else not using append()
Like:
a = [1,3]
b = [2,4]
How about this:
l = [[[1,2],[3,4]]]
a = []
b = []
for x in l[0]:
a.append(x[0])
b.append(x[1])
There is more pythonic way to do this, but code above is written to make it understandable.
If you write
a=[List[0][0][0], List[0][1][0]]
b=[List[0][0][1], List[0][1][1]]
You get what you want. You can define it in a loop, of course
l = [[[1,2],[3,4]]]
a = [x[0] for x in l[0]]
b = [x[1] for x in l[0]]
List comprehensions are essentially for loops in lists they pretty much read like a sentence:
do x FOR x in OTHER_LIST (and wrap that in a list)
I have a list of tuples, and I want to remove duplicate tuples. Something like this.
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
I want the output something like this :
y = [['aaron','jeng'],['sdf','wqd']]
How can I do that in an easy way? I can write code to do that, but is there any inbuilt function for this?
Edit 1 : As everyone has suggested, I'm sorry to call them tuples. I meant a list of lists. Thank You.
Your x value does not contain a list of tuples, but a list of lists. If it did contain a list of tuples:
x = [('aaron','jeng'),('sdf','wqd'),('aaron','jeng')]
out = set([i for i in x])
print(list(out))
[('aaron', 'jeng'), ('sdf', 'wqd')]
That's a list of lists... But no matter, you can use a temporary set to make sure there are no repeats:
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
seen = set() # store here the visited tuples
y = [e for e in x if tuple(e) not in seen and not seen.add(tuple(e))]
# [['aaron', 'jeng'], ['sdf', 'wqd']]
If you convert your inner lists to tuples upfront it will have a considerably better performance.
If you don't need to preserve the order, then just convert the inner lists to tuples and turn your x to a set().
This would be easy with a list of tuples, you would simply need set(x). Since your list is a list of lists, and not a list of tuples, you can convert them first:
set(tuple(i) for i in x)
returns:
{('aaron', 'jeng'), ('sdf', 'wqd')}
Or, if you want to reconvert to a list of lists as you had it:
[list(t) for t in (set(tuple(i) for i in x))]
# [['aaron', 'jeng'], ['sdf', 'wqd']]
You can use enumerate and any:
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
new_x = [[a, b] for i, [a, b] in enumerate(x) if not any(c == b for _, c in x[:i])]
Output:
[['aaron', 'jeng'], ['sdf', 'wqd']]
You do not have tuples, you have lists inside lists.
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
uniques = list (set ( tuple(a) for a in x))
Is a generator expression fed into a set thats then fed to a list resulting in
[('aaron', 'jeng'), ('sdf', 'wqd')]
What about converting to a dict , Because dict can have unique keys :
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
print({tuple(i):i for i in x}.values())
output:
[['aaron', 'jeng'], ['sdf', 'wqd']]
I have to create a list of lists (each inner list has n fixed elements). Right now, for n=3 I am doing this:
my_list = []
for x in range(min_inner max_inner + 1):
for y in range(min_outer, max_outer + 1):
for z in range(fixed_param):
my_list.append([x, y, z])
When I tried list comprehension, something like:
[[x,y,z] for x in range(1,4), y in range(1,4), z in range (4)]
I get a name error
NameError: name 'z' is not defined
Is there a list comprehension way of doing that? Considering that n can be any number (though not necessarily arbitrarily large)
You need to loop over your range objects inside the list comprehension too.
[[x,y,z] for x in range(1,4) for y in range(1,4) for z in range (4)]
Also as a more concise way you could use itertools.product() to achieve the same result:
from itertools import product
list(product(range(1,4),range(1,4),range(4)))
Note that itertools.product() returns an iterator object which is pretty more optimized (in terms of memory usage) than list comprehension which returns a list. And if you just want to iterate over the result you don't need to convert the result to list. Otherwise the list comprehension will performs faster.
I have a list of tuples like
[('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')]
How can I get the value EVTTIMESTAMP?
Generally you can loop through your list.
For example:
myList = [('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')] ;
for x in range(0,len(myList)):
print(myList[x][0])
This will print:
EVTTIMESTAMP
SUBSYTEMID
VRR
Inside the loop you can put some logic to compare each element with the one you want to perform an operation on and only return the match.
For example:
for x in range(0,len(myList)):
if myList[x][0] == "EVTTIMESTAMP":
b = myList[x][0]
##do something with b
If you know the exact position of the item, then you can just call it like:
b = myList[0][0] etc...
For example:
print(myList[0][0]) will print: EVTTIMESTAMP
Hope this helps
for getting all the 2nd value of the tuples you can use
a = [('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')]
[x[1] for x in a]
for getting specific value of "EVTTIMESTAMP" u can use if condition
[x[1] for x in a if x[0] == 'EVTTIMESTAMP']
Say I have this code in Python. I'm a Perl programmer, as you may be able to tell.
# Both list1 and list2 are a list of strings
for x in list1:
for y in list2:
if y in x:
return True
return False
What's a more Pythonic way to handle this? I assume a list comprehension could do it well, but I can't get my head around the "process two separate lists" part of this.
To convert two nested loops into a nested comprehension, you just do this:
[<expression> for x in list1 for y in list2]
If you've never thought through how list comprehensions work, the tutorial explains it:
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
In other words, the clauses from left to right in a comprehension match up with statements from top/outside to bottom/inside, and that's all there is to it.
This blog post attempts to put the same idea in yet another way, in case you haven't got it yet.
But here, you don't have an expression, you have a statement.
But you have an expression in there, the y in x part of the statement, and what you want to do is return True if it's every true for any value, which is exactly what any does. So:
return any([y in x for x in list1 for y in list2])
And really, you don't want to build the list here, just iterate over the values, so drop the square brackets to make it a generator expression instead:
return any(y in x for x in list1 for y in list2)
For the simple case of just iterating the cartesian products of multiple iterables, you may want to use itertools.product instead. In this case, I don't think it makes things any simpler or more readable, but if you had four lists instead of two—or an unpredictable-in-advance number of them—that might be a different story:
return any(y in x for x, y in product(list1, list2))
No, a list comprehension can't do it well. You want a boolean result, list comprehensions are for creating lists (and they don't really do early exit). You could use a generator comprehension:
return any(y in x for x, y in itertools.product(list1, list2))
or if you really like using standard libraries for everything (or you think like a functional programmer):
from itertools import starmap, product
from operator import contains
return any(starmap(contains, product(list1, list2))
Steve and abamarts answers are explaining what you asked explicitly, i would try to address what you implied regarding list comprehensions.
A "nested" list comprehension is nothing more then your original nested for loop, but with the twist, that the most inner-block moves up to the top!
for x in list1:
for y in list2:
if y in x:
return True
else:
return False
becomes:
[True if y in x else False for x in list1 for y in list2]
So the for-loops remain more or less in order:
[for x in list1 for y in list2]
then prepend the if-clause:
[if y in x else False for x in list1 for y in list2]
and finally prepend the result for the if-statement to be True:
[True if y in x else False for x in list1 for y in list2]
a nested example:
tpl_list = []
for element in vector:
for x, y in element:
if (x**2+y**2) < 1:
tpl_list.append((1/x, 1/y))
else:
tpl_list.append((x,y))
as a list comprehension (building in steps)
[for e in vector for x,y in e]
[if (x**2+y**2) < 1 else for e in vector for x,y in e]
[(1/x, 1/y) if (x**2+y**2) < 1 else (x,y) for e in vector for x,y in e]