简体   繁体   中英

select sub item in a tuple list in python

Here I have one list like this:

a = [[13245,0.123],[12435,0.435],[12345,0.799],[98775,0.573]...]

I want to use the first item in every tuple as x axis, and the second item in every tuple as y axis to plot a figure.

like x = [13245,12435,12345,68775] y = [0.123,0.435,0.799,0.573]

How can I select them out?

最简单的方法可能是使用zip

x, y = zip(*a)

Try this:

x = [tmplist[0] for tmplist in a]
y = [tmplist[1] for tmplist in a]

Also, [] doesn't define tuples, but lists. But in your case the handling is equal.

use:

x = []
y = []
for e in a:
    x.append(e[0])
    y.append(e[1])

edit: I didn't even remeber zip(), but it is certainly the best way of doing it:

x, y = zip(*a)

python have a realy powerfull function for this :)

zip

try it

x,y = zip(*a)

the * is the key. see the doc for more details

I'm not sure why your converting to ax list and ay list to plot coordinates. Would something as simple as this work?

for x,y in a:
  plot(x,y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM