Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Please note that I have tried to use the answers provided on this forum, plus other web sources before posting this. I'm pretty much a beginner.
Using Py 2.7.10
A = [9,3,7]
B = [5,1,8]
C = [1,2,1]
D = [A,B,C]
How can I first 1) sort by A(ascending), 2) by B(ascending) and 3) by C(ascending). In this case the values are A (x-coordinate), B (Y-coordinate) and C (z-coordinate). I have tried using a function, but it rearanged the A, B and C variables, however I would like the first element of both A, B, and C to stick together since they belong to each other.
Thanks in advance.
I believe that first you need to translate your A,B and C lists into a list of (x,y,z) co-ordinates. You can use zip like so:
coords = list(zip(A,B,C))
Then - sort the list in the way you wish, using sorted:
coords_sorted_by_x = sorted(coords,key=lambda c:c[0])
[(3, 1, 2), (7, 8, 1), (9, 5, 1)]
coords_sorted_by_y = sorted(coords,key=lambda c:c[1])
[(3, 1, 2), (9, 5, 1), (7, 8, 1)]
coords_sorted_by_z = sorted(coords,key=lambda c:c[2])
[(9, 5, 1), (7, 8, 1), (3, 1, 2)]
If you need to retrieve the x,y and z co-ordinates into separate lists you can use zip(*) e.g.:
A_new, B_new, C_new = zip(*coords_sorted_by_z)
You note that you are using Python 2.7. Although I heartily recommend that you use Python 3, the main difference is that you do not need to do list(zip(...)) but simply zip(...), because in python 2, zip returns a list.
As you will see if you run it, the code provided works for 2 and 3.
You may use the default sort function available for Python lists.
A.sort() // o/p : [3, 7, 9]
B.sort() // o/p : [1, 5, 8]
C.sort() // o/p : [1, 1, 2]
Then doing the following should suffice:
for e in zip(A,B,C):
print e
output:
(3, 1, 1)
(7, 5, 1)
(9, 8, 2)
If need output in listformat:
for e in zip(A,B,C):
print list(e)
output:
[3, 1, 1]
[7, 5, 1]
[9, 8, 2]
So i am assuming that A is a list of x-, B of y- and C of z-coordinates. You want to sort the columns in your matrix, so that numbers stay vertically together.
First i would transpose your matrix:
matrix = [
[9,3,7],
[5,1,8],
[1,2,1]
]
matrix = zip(*matrix)
and then sort this list. As zondo said, sort does what you want by default in this case:
matrix.sort()
And lastly transpose the matrix back:
matrix = zip(*matrix)
Related
I am relatively new to programming, and have this problem:
There are two lists: C=[i,i,k,l,i] and D =[m,n,o,p,q]
I want to select the index of the minimum element of C. If k or l is the minimum, it is quite simple, since the min function will directly return the desired index. But if i is the minimum, there are several possibilities. In that case, I want to look at list D's elements, but only at the indices where i occurs in C. I then want to chose my sought-after index based on the minimum of those particular elements in D
I thought of the following code:
min_C = min(C)
if C.count(min_C) == 1:
soughtafter_index = C.index(min_C)
else:
possible_D_value = []
for iterate in C:
if iterate==min_C:
possible_index = C.index(iterate)
possible_D_value.append(D[possible_index])
best_D_value = min(possible_D_value)
soughtafter_index = D.index(best_D_value)
(Note that in the problem C and D will always have the same length)
I havent had a chance to test the code yet, but wanted to ask whether it is reasonable? Is there a better way to handle this? (and what if there is a third list-- then this code will get even longer...)
Thank you all
Try this:
soughtafter_index = list(zip(C, D)).index(min(zip(C,D)))
UPDATE with the required explanation:
>>> C = [1, 5, 1, 3, 1, 4]
>>> D = [0, 1, 1, 3, 0, 1]
>>> list(zip(C, D))
[(1, 0), (5, 1), (1, 1), (3, 3), (1, 0), (4, 1)]
>>> min(zip(C, D))
(1, 0)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a set of tuples:
(1, 3, 6)
(5, 2, 4)
...
(8, 1, 9)
I can get combinations of middle (or first or last) values whose sum is below a certain value:
def func(tuples, maxVal):
values = [i[1] for i in tuples]
result = [seq for s in range(len(values), 0, -1) for seq in itertools.combinations(values, s) if sum(seq) <= maxVal]
print(result)
but i'd like to be able to keep track of which tuples the values came from, so instead of just returning sets of values with appropriate sum, i want to return whole tuples which those values came from. Not sure how to do that.
How about
from itertools import combinations
def func(tuples, maxVal):
return [seq for s in range(len(tuples), 0, -1)
for seq in combinations(tuples, s)
if sum(t[1] for t in seq) <= maxVal]
tuplesset = {(1, 3, 6), (5, 2, 4), (8, 1, 9)}
print(func(tuplesset, 4))
The printout from that is
[((1, 3, 6), (8, 1, 9)), ((5, 2, 4), (8, 1, 9)), ((1, 3, 6),), ((5, 2, 4),), ((8, 1, 9),)]
which seems to be correct.
The main differences between my routine and yours is that I leave out the values variable (the middle values in your tuples) and have the expression sum(t[1] for t in seq) rather than sum(seq) for summing the middle values of the tuples. I also broke your one long line into multiple shorter lines for legibility and to follow PEP8 better.
You could use a dictionary mapped to pairs if you really want to save the tuples instead of just saving the indices:
{(x, x, x) : ( (z,z,z), (y,y,y) ), ... }
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 5 years ago.
Improve this question
I really want to know how to extract all the element from two lists and multiply each other. For example, if there are two lists
A=[1,3,5,7,9]
B=[2,4,6,8]
I want to do 1X2, 1X4, 1X6, 1x8, 3x2... etc.
One element from A X one element from B.
I tried to use zip but because of length difference, I couldn't get right answers.
SInce your question seems to want the cartesian product between two lists, you can use itertools.product to bind every element from A with every element from B:
>>> from itertools import product
>>> A = [1,3,5,7,9]
>>> B = [2,4,6,8]
>>> list(product(A, B))
[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8), (9, 2), (9, 4), (9, 6), (9, 8)]
Then if you want to multiply the the two elements in each tuple, you can do this:
>>> [x * y for x, y in product(A, B)]
[2, 4, 6, 8, 6, 12, 18, 24, 10, 20, 30, 40, 14, 28, 42, 56, 18, 36, 54, 72]
To get a random value from a list, you can do something similar to the following:
import random
lst = [10,20,30]
x = random.choice(lst)
Importing the random library gives you access to a ton of random generation tools. Per the random library documentation (https://docs.python.org/3/library/random.html), random.choice(seq) returns a random element from a non-empty sequence, such as a list. Thus, the code above randomly selects an element from lst and assigns that value to the variable x.
I don't want to give the solution away until you've tried using the random library, so I'll let you figure out how to use the information above.
You can use for loops:
Operation for each item in A with each item in B:
A=[1,3,5,7,9]
B=[2,4,6,8]
C = [] #Create an empty list
for i in A: #iter each element in A
for j in B: #iter each element in B
mult = i * j
C.append(mult) #Append the result in the list C
print(C)
Operation with a random item in A with each item in B:
import numpy as np
A=[1,3,5,7,9]
B=[2,4,6,8]
C = [] #Create an empty list
for i in A: #iter each element in A
i = np.random.randint(len(A)) #Chose a random number from A
for j in B: #iter each element in B
mult = A[i] * j #Multiply a random number from A with each element in B
C.append(mult) #Append the result in the list C
print(C)
This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 7 years ago.
I'm trying to turn a list into pairs, but only for as long as possible (i.e. my list can be odd, in that case I want to ignore the last element).
E.g. my input is x = [0, 1, 2, 3, 4], which I would want to turn into [(0, 1), (2, 3)]. Similarly, x = [0, 1, 2, 3, 4, 5] should become [(0, 1), (2, 3), (4, 5)].
What I'm currently doing is [(x[i], x[i+1]) for i in range(0, len(x), 2)]. This breaks, as range(0, len(x), 2) still includes x[-1] if len(x) is odd. Note that something of the form [(l, r) for l, r in ...] would also be preferable, rather than having to fiddle with indices.
Bonus points: Here's some more context. I'm not completely ignoring the last element of an odd sequence, of course. I'm applying a function to each pair, but I do not want to apply this function H to the singleton element. Currently, I'm doing the following:
next_layer = [H(layer[i], layer[i+1]) for i in range(0, len(layer), 2)]
if len(layer) & 1: # if there is a lone node left on this layer
next_layer.append(layer[-1])
An extra elegant solution would incorporate this into the above as well.
Use a zip
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.
>>> a = [1, 2, 3, 4, 5]
>>> b = [0, 1, 2, 3, 4, 5]
>>> zip(a[::2], a[1::2])
[(1, 2), (3, 4)]
>>> zip(b[::2], b[1::2])
[(0, 1), (2, 3), (4, 5)]
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 8 years ago.
Improve this question
I have been given a whole stack of data (900 tuples to be exact) within each of these tuples there are 12 elements stored.
I need to load the second element in the tuple.
How would I extract the second element from every all of the 900 tuples? Any help or suggestions how to do this would be appreciated.
t1 = (something here)
t2 = (something here)
.
.
.
t900= (something here)
l = [t1, t2 ,... ,t900]
a = [i[1] for i in l]
print a
Is this what you want? Tell me if it works.
...
yourTuples = [(....), (.....)]
result = []
for item in yourTuples:
result.append(item[1])
print result
Map over the list:
list_of_tuples = [(..., ...), (..., ...), ...]
second_elements = map(lambda x: x[1], list_of_tuples)
You can easily do that using a python package numpy
see the sample code below,
import numpy
initial_list = [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), ]
array = numpy.array(initial_list)
print array[:,1]
If you have stack of data in list form, you can simply do this using zip:
lt=[(1,2,3),(4,5,6),(7,8,9)]
print zip(*lt)[1]
output:
(2, 5, 8)