Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

python - 解开列表清单[重复项](Unwrap a list of list [duplicate])

I have this list:

(我有这个清单:)

fxrate = 
[[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
 [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
 [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]

I would like to make a list like this by using Python:

(我想使用Python列出这样的列表:)

[[9.6587, 9.9742, 9.9203, 10.1165, 10.1087],
 [10.7391, 10.8951, 11.1355, 11.561, 11.7873],
 [8.61, 8.9648, 9.0155, 9.153, 9.1475]]

Needless to say I'm fairly new to Python and programming in general.

(毋庸置疑,我对Python和一般编程还是相当陌生的。)

However all I end up with is either one list of values but not at three sets of lists

(但是,我最终得到的只是一个值列表,而不是三组列表)

  ask by victor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you want to do is flatten your list, Just use a list comprehension.

(您要做的是将列表弄平,只需使用列表理解即可。)

This will take any list of lists you have and flatten it such that, Your list only has a depth of one.

(这将获取您拥有的任何列表列表,并将其展平,以使您的列表只有一个深度。)

ie [["foo"], ["bar"],["List_of_lists"]] would become ["foo", "bar", "complex_lists"]

(即[["foo"], ["bar"],["List_of_lists"]]将变为["foo", "bar", "complex_lists"])

flat_list = [item for sublist in l for item in sublist]

As specified here

(作为指定在这里)

You can format this into your code as necessary.

(您可以根据需要将此格式设置为代码。)

Like so:

(像这样:)

fxrate = 
   [[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
   [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
   [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]
flat_fxrate = [[item for sublist in fxrate[0] for item in sublist],[item for sublist in fxrate[1] for item in sublist],[item for sublist in fxrate[2] for item in sublist]]

For example.

(例如。)

Since you want it split in three or if you plan to upscale it.

(由于您希望将其拆分为三部分,或者如果您打算对其进行扩展,则可以使用。)

Or to make it more legible, you can use a loop and append each part.

(或者使它更清晰,可以使用循环并附加每个部分。)

Like so.

(像这样)

Note: In general it's a lot better to use a loop because then no matter what the size of this list is, it will always work.

(注意:通常,使用循环会更好,因为无论此列表的大小如何,它都将始终有效。)

flat_fxrate = []
fxrate = 
   [[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
   [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
   [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]
for x in fxrate:
    flat_fxrate.append([item for sublist in x for item in sublist])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...