Hello I have a few lists and im trying to create a new list of the highest values repsectively. for an example, these are the lists:
list1 = 5, 1, 4, 3
list2 = 3, 4, 2, 1
list3 = 10, 2, 5, 4
this is what I would like it to return:
[10, 4, 5, 4]
I thought that I could do a something like this:
largest = list(map(max(list1, list2, list3)))
but I get an error that map requires more than 1 argument.
I also thought I could write if, elif statements for greater than but it seems like it only does the first values and returns that list as the "greater value"
thanks for any help
This is the "zip splat" trick:
>>> lists = [list1, list2, list3]
>>> [max(col) for col in zip(*lists)]
[10, 4, 5, 4]
You could also use numpy arrays:
>>> import numpy as np
>>> np.array(lists).max(axis=0)
array([10, 4, 5, 4])
You have used map incorrectly. Replace that last line with this:
largest = list(map(max, zip(list1, list2, list3)))
In map, the first argument is the function to be applied, and the second argument is an iterable which will yield elements to apply the function on. The zip function lets you iterate over multiple iterables at once, returning tuples of corresponding elements. So that's how this code works!
Using map's iterableS argument has an implicit zip-like effects on the iterables.
map(max, *(list1, list2, list3))
Related
I have a very simple code where I want to loop through two lists at the same time. However, this gives me a ValueError: too many values to unpack.
def testing_something():
list1 = [1,2,3,4,45]
list2 = [1,4,4]
return list1, list2
for q,z in testing_something():
print (q,z)
The output of testing_something() is ([1, 2, 3, 4, 45], [1, 4, 4]), so I can imagine to be able to loop simultaneously through this output, with q in my case being [1, 2, 3, 4, 45] and z being [1,4,4]. Why does this raise a ValueError?
you can't use a single for to iterate over two lists at the same time. You should use zip function
def testing_something():
list1 = [1,2,3,4,45]
list2 = [1,4,4]
return list1, list2
for q,z in zip(testing_something()):
print(q)
print(z)
Note that zip will iterate until the lists have elements: if it finishes iterating over one, it will stop iterating. This is solved with itertools.zip_longest, which would output None in correspondence of the out-of-bound index: should you want to use it, you have to import the itertools module
If you want q=[1, 2, 3, 4, 45] and z=[1,4,4] in the first (and only) iteration of the for loop, you should return [[list1, list2]].
However, if you plan to only have one pair of lists returned, you can skip the for loop altogether (and keep the code you posted in the question):
q, z = testing_something()
print(q, z)
you can't iterate over single variable as your doing in your for loop,this is the easy way to q,z as your lists.
def testing_something():
list1 = [1,2,3,4,45]
list2 = [1,4,4]
return list1, list2
q,z=testing_something()
print q
print z
I have two lists filled with integers. I wish to add them together such that:
the output list has no duplicate elements,
is in order, and
contains the union of both lists.
Is there any way to do so without creating my own custom function? If not, what would a neat and tidy procedure look like?
For instance:
list1 = [1, 10, 2]
list2 = [3, 4, 10]
Output:
outputlist = [1, 2, 3, 4, 10]
Try this:
combined = [list1, list2]
union = list(set().union(*combined))
This takes advantage of the predefined method (.union()) of set() , which is what you need here.
combined can have as many elements inside it, as the asterisk in *combined means that the union of all of the elements is found.
Also, I list()ed the result but you could leave it as a set().
As #glibdud states in the comments, it's possible that this might produce a sorted list, but it's not guaranteed, so use sorted() to ensure that it's ordered. (like this union = sorted(list(set().union(*combined))))
l1 = [1, 10, 2]
l2 = [3, 4, 10]
sorted(list(set(l1 + l2)))
>>> [1, 2, 3, 4, 10]
I have a spectra of wavelengths as a list and some number of other lists I use in a formula (using tmm.tmm_core). Is there something more efficient than iterating through the wavelength if I'm just basically doing the same thing for all wavelengths?
Example
def go(n, thk, theta):
#do stuff
return(something)
wv = [1, 2, 3, 4]
a_vec = [3, 7, 3, 9]
b_vec = [6, 5, 9, 3]
c_vec = [0, 1, 8, 9]
theta = 0
th = [10, 1, 10]
final = []
for i in range(len(wv)):
n = [a[i], b[i], c[i]]
answer = go(n, th, theta)
final.append(answer)
in reality there are maybe 5000-10000 rows. It just seems to lag a bit when I press go and I assume it's because of the iteration. Pretty new to optimizing so I haven't used any benchmarking tools or anything.
I think you're looking for the map function in Python!
>>> list1 = [1,2,3,4]
>>> list2 = [5,6,7,8]
>>> map(lambda x,y: x+y, list1, list2)
[6, 8, 10, 12]
it takes in a function (in the above case, an anonymous lambda function), one or more lists and returns another list. At each iteration within the function, both lists are iterated and the result is added to the new list. You don't need to limit yourself to the expressive power of a lambda statement; you can also use globally defined functions as in the case below:
>>> def go(a,b,c):
... return a+b+c
...
>>> map(go, list1,list2, range(9,13))
[15, 18, 21, 24]
You can put all of your lists within a custom list like C_list and use map to create a new list all_len contain the length of all lists then use a list comprehension to create the list final :
all_len=map(len,C_list)
final =[[go([a[i], b[i], c[i]], th, theta) for i in range(li)] for li in all_len]
Also if the length of a and b and c are equal you can use zip function to zip then and refuse of multiple indexing :
all_len=map(len,C_list)
z=zip(a,b,c)
final =[[go(z[i], th, theta) for i in range(li)] for li in all_len]
If you have to perform an operation on every item in the list, then you're gonna have to go through every item in the list. However, you could gain speed through the use of list comprehensions: List Comprehensions
I am trying to figure out how to append multiple values to a list in Python. I know there are few methods to do so, such as manually input the values, or put the append operation in a for loop, or the append and extend functions.
However, I wonder if there is a more neat way to do so? Maybe a certain package or function?
You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append() to append a single value, and list.extend() to append multiple values.
Other than the append function, if by "multiple values" you mean another list, you can simply concatenate them like so.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.
There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.
if the number of items was saved in a variable say n. you can use list comprehension and plus sign for list expansion.
lst = ['A', 'B']
n = 1
new_lst = lst + ['flag'+str(x) for x in range(n)]
print(my_lst)
>>> ['A','B','flag0','flag1']
One way you can work around this type of problem is -
Here we are inserting a list to the existing list by creating a variable new_values.
Note that we are inserting the values in the second index, i.e. a[2]
a = [1, 2, 7, 8]
new_values = [3, 4, 5, 6]
a.insert(2, new_values)
print(a)
But here insert() method will append the values as a list.
So here goes another way of doing the same thing, but this time, we'll actually insert the values in between the items.
a = [1, 2, 7, 8]
a[2:2] = [3,4,5,6]
print(a)
I'm using python 2.7 I'm trying to figure out a way to change the names of my lists automatically.
Let me explain i have multiple lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 9, 3]
list3 = [8, 4, 3, 2, 1]
I would like to call the lists in a loop to determine which lists contain or do not contain a particular number.
My first thought was
x = "list" + str(i) # (where i iterates in the loop)
print x
However, using the above code only gave me the string "list1"(when i=1).
What I want is to be able to call the list that is named list1 and use the .count() operator to determine whether or not the number exists if it doesn't i want to call the next list until I'm out of lists(there will eventually be up to 30 lists).
Thanks,
Ryan
You shouldn't approach it like this. Put your lists in a container to iterate over them instead:
In [5]: for l in (list1, list2, list3):
...: print l.count(2)
...:
1
0
1
What you could do in a real-life use case is create a list of lists and fill it dynamically.
Then to get the first list that contains a given number, you could do:
In [6]: lists = [list1, list2, list3]
In [7]: next(l for l in lists if 9 in l)
Out[7]: [4, 5, 9, 3]
put the list in dict:
list1 = [1,2.4]
list2 = [2,5,6]
dlist = {1:list1,2:list2}
for k in dlist:
print dlist[k]