This question already has answers here:
python - get list of tuples first index?
(5 answers)
Closed 6 years ago.
I have a list of tuples in this format:
my_list = [(1,4),(3,6),(10,7)]
I want to print the second elements of each tupple:
4,6,7
I can access those values as:
my_list[0][1]
my_list[1][1]
my_list[2][1]
But that isn't a reasonable approach for any reasonable size list, for now, and doing using list comprehension:
[x[1] for x in my_list ]
Is there any solution that doesn't imply to use a loop?
something like:
my_list[:][1]
I tried to do it that way but got:
(3, 6)
[:] just creates a copy of the list, so [1] indexes that copy. And no, outside of NumPy arrays, there is technically no way to avoid a loop. The loop may be done in C code in a function like map(), but there's going to be a loop anyway.
Using map() for example applies a callable for each element in your input list:
map(lambda nested: nested[1], my_list)
or
from operator import itemgetter
map(itemgetter(1), my_list)
Both work in Python 2, in Python 3 you need to wrap the map() call in a list() call to drive the iteration.
Either way, I find a list comprehension to be clearer here anyway.
As mentioned in python get list of tuples first index
try with zip
my_list = [(1,4),(3,6),(10,7)]
print zip(*my_list)[1]
(4, 6, 7)
Related
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 10 months ago.
I have a code which takes input of the users and creates a nested list.
List = [list 1, list2, list 3,.....]
The list 1, list 2, list 3 and so on are dynamic and can keep increasing or decreasing.
So far my code output is:
All_data = [[a,b],[c,d],[1,2],[3,4],.....]
The output that I want (for the dynamic nested list):
All_data = [a,b,c,d,1,2,3,4,......]
Can anyone suggest me a solution to solve this?
You can use itertools.chain:
itertools.chain(*All_data)
Or:
itertools.chain.from_iterable(All_data)
This creates an iterator, if you want to get a list:
list(itertools.chain.from_iterable(All_data))
You can use numpy.concatenate(). It will condense the nested list into a single list.
If your nested list is dynamic and can grow exponentially, then I will suggest to use itertools.chain.from_iterable() from itertools library. It will be faster because it will not convert the list into a numpy array like the first option.
This question already has answers here:
Appending item to lists within a list comprehension
(7 answers)
Closed 2 years ago.
I'm trying to iterate through a list and generate another list. is this achievable using list comprehension?
source = ['1/2','1/3','1/4']
port_hdl_dict = {'1/2':'1/1/2','1/3':'1/1/3','1/4':'1/1/4','1/5':'1/1/5'}
def getSourcePortlistIxia(source_list,port_hdl_dict):
source_port_list = []
for i in source_list:
source_port_list.append(port_hdl_dict[i])
return(source_port_list)
res = getSourcePortlistIxia(source,port_hdl_dict)
print(res)
This i tried to acheive this using liist comprehension
source_port_list = []
my_list = [source_port_list.append(port_hdl_dict[i]) for i in source]
print(my_list)
but this prints the output as
['1/1/2', '1/1/3', '1/1/4']
[None, None, None]
am I doing anything wrong here? how do we achieve this?
my_list = [port_hdl_dict.get(v) for v in source]
Generating a list, or another iterable structure from a list is one of the best use cases for list comprehension. The problem with your code is that the append operation doesn't return anything. Because that's what you're storing inside my_list, when you print my_list, you get [None, None, None]
Furthermore, it seems to me that what you're actually trying to do is get all values from a dictionary, for a given set of keys.
You can achieve that by, instead of using a third list that you append to, returning the value in the dictionary, inside the list comprehension, as such:
my_list = [port_hdl_dict[i] for i in source]
The above is a very naive example with no validation. So, for example, if i was not a valid key inside port_hdl_dict, then your code would raise an exception.
You can add some simple validation by simply checking i is in port_hdl_dict
my_list = [port_hdl_dict[i] for i in source if i in port_hdl_dict]
This question already has answers here:
Divide elements of a list by integer with list comprehension: index out of range
(5 answers)
Closed 3 years ago.
I have a list of numbers and i need to divide them all by a specific number.
Lets say i want to divide all of the items by 2
list = [1,2,3,4,5,6,7]
wanted_list = [1/2,2/2,3/2,4/2,5/2,6/2,7/2]
I attempted a for loop that changes each but it didnt work for some reason like it didnt do the operation.
list = [1,2,3,4,5,6,7]
wanted_list = [i/2 for i in list]
print(wanted_list)
I assume san's answer is the best approach, as it utilizes lists comprehension and in that case a new list is created automatically, however considering what you wrote, you can as well use a for loop, only you need to store the result somewhere, ex:
data = [2, 4, 6]
wanted_data = []
for d in data:
wanted_data.append(int(d/2))
print(wanted_data)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to iterate over two lists - python
I want to iterate over two items at the same time, an iteration that in my mind looks like this:
for elem1 in list 1 and for elem2 in list2:
do something to elem1; do something to elem2
This syntax, however, is not acceptable. To be clear, I'm not talking about nested for loops, because then I'd be iterating over an entire list for every element in the first list. I want to iterate over the two lists (or whatever) in tandem. Is there a pythonic way to do this?
Use zip():
for elem1, elem2 in zip(list1, list2):
If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.
On python 2, zip() results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip() itself already returns an iterator.
If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:
from itertools import izip_longest
for elem1, elem2 in izip_longest(list1, list2):
This question already has answers here:
How to sort a list of lists by a specific index of the inner list?
(12 answers)
Closed last year.
I have a list of lists (can't be tuples since I have to generate it dynamically) and it is structured as a list of lists of one int and one float Like so:
[[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
I want to get it sorted but I have only managed to get the built in sorting function to sort it by the first element of the lists or not do anything, but I need to sort them by the second element of the list and I don't want to implement my own sorting function. So an example of what I would want is:
[[1,1.0345],[3,4.89],[2,5.098],[2,5.97]]
Could someone tell me how to get one of the built in sorting functions to do this?
Pass the key argument.
L.sort(key=operator.itemgetter(1))
>>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
>>> l.sort(key=lambda x: x[1])
>>> l
[[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]
How about using they key parameter of sorted...
sorted_list = sorted([[1,1.0345],[3,4.89],[2,5.098],[2,5.97]], key=lambda x: x[1])
This tells python to sort the list of lists using the item at index 1 of each list as the key for the compare.