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)
Related
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
I have a list like this, with an even number of elements:
straight_list = [1, 2, 3, 4, 5, 6]
There are six items in this list. I'd like to group them into three pairs, like this:
paired_list = [(1, 2), (3, 4), (5, 6)]
What's the best way to do this? More generally, given a list with 2*n items, what's the best way to create a list of n pairs? I have come up with the following:
straight_list = [1, 2, 3, 4, 5, 6]
paired_list = []
for i in range(len(straight_list)//2):
j = i*2
pair = (straight_list[j], straight_list[j+1])
paired_list.append(pair)
print(paired_list)
# [(1, 2), (3, 4), (5, 6)]
I also can make it work like this, though it's a tongue-twister:
[tuple(x) for x in list(np.array(straight_list).reshape(len(straight_list)//2,2))]
# [(1, 2), (3, 4), (5, 6)]
Is there a more elegant, functional, and/or "Pythonic" way to create this list of pairs?
(In some ways, this is almost an inverse of this question: "How to make a flat list out of a list of lists?")
How about a simple list comprehension?
paired_list = [(straight_list[i], straight_list[i+1]) for i in range(0, len(straight_list), 2)]
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 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)
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 9 years ago.
Improve this question
I have a list of lists with data like credit pays schedule:
[ [pay_number, pay_date, pay_amount], [pay_number, pay_date, pay_amount], e.t.c ]
how can I get next pay_date from it ?
You just need to iterate over the list:
thelist = [ [pay_number, pay_date, pay_amount], [pay_number, pay_date, pay_amount], ... ]
for sub_list in thelist:
current_pay_date = sub_list[1]
# do something with current_pay_date
If you want to access the next pay_date:
for i in range(len(thelist)):
sub_list = thelist[i]
current_pay_date = sub_list[1]
next_sub_list = thelist[i+1]
next_pay_date = next_sub_list[1]
Hope this was what you were looking for.
You can use the min function to get the element from your list which is the closest to today by using a custom key function:
>>> items = [[1, datetime.date(2014, 2, 28), 1], [2, datetime.date(2014, 2, 7), 2], [3, datetime.date(2014, 2, 14), 3]]
>>> min(items, key=lambda x: x[1] - datetime.date.today())
[2, datetime.date(2014, 2, 7), 2]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
list = [1,2,3,4]
I would like to get a result of below and store them in csv file. ( 6 rows total )
1,2
1,3
1,4
2,3
2,4
3,4
Is there a function to this or how can I accomplish and store this in csv file ?
itertools is your friend...
http://docs.python.org/2/library/itertools.html
>>> import itertools
>>> x = [1, 2, 3, 4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Use itertools.combinations. It's builtin in Python 2.6+.
import itertools
pairs = itertools.combinations(list, 2)
One option is to use itertools.permutations and a list comprehension:
>>> [(x, y) for x, y in itertools.permutations(mylist, 2) if x < y]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
The condition x < y ensures you only get the permutations where x is lower than y.
The better option is to use itertools.combinations(mylist, 2).
This is simple enough to do it yourself:
l=[1,2,3,4]
for i in range(0,len(l)):
for j in range (i+1,len(l)):
print l[i],l[j]
But solutions using itertools can be generalized much easier.