将平面列表转换为元组列表 [英] Converting a flat list to a list of tuples

查看:90
本文介绍了将平面列表转换为元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个单一的清单:

['''',1,''b'',2,''c'',3]

你如何有效地获得

[[''a'',1],[''b'',2],[''c'',3]]


我在考虑以下内容:

(列表中的密钥,数字):

打印密钥,编号


但它不起作用......


谢谢

Say you have a flat list:
[''a'', 1, ''b'', 2, ''c'', 3]

How do you efficiently get
[[''a'', 1], [''b'', 2], [''c'', 3]]

I was thinking of something along the lines of:
for (key,number) in list:
print key, number

but it''s not working...

Thank you

推荐答案

metiu uitem写道:
metiu uitem wrote:
说你有一个单一的清单:
['''',1,''b '',2,''c'',3]

你如何有效地获得
[['''',1],[''b'',2] ,[''c'',3]]
Say you have a flat list:
[''a'', 1, ''b'', 2, ''c'', 3]

How do you efficiently get
[[''a'', 1], [''b'', 2], [''c'', 3]]




这很有趣,我认为你的主题是''元组列表''。我会

回答主题中的问题而不是正文中的问题:



That''s funny, I thought your subject line said ''list of tuples''. I''ll
answer the question in the subject rather than the question in the body:

aList = ['''',1,''b'',2,''c'',3]
it = iter(aList)
zip(它,它)
aList = [''a'', 1, ''b'', 2, ''c'', 3]
it = iter(aList)
zip(it, it)



[(''a'',1),(''b'',2),(''c'',3 )


[(''a'', 1), (''b'', 2), (''c'', 3)]


谢谢你的答案......是的,这个例子错了!

Thanks for the answer... yes the example was wrong!


On Tue,2005年11月22日02:57:14 -0800,metiu uitem写道:
On Tue, 22 Nov 2005 02:57:14 -0800, metiu uitem wrote:
说你有一个单一的清单:
[''a'' ,1,''b'',2,''c'',3]

你如何有效地获得
[['''',1],['' b'',2],[''c'',3]]
Say you have a flat list:
[''a'', 1, ''b'', 2, ''c'', 3]

How do you efficiently get
[[''a'', 1], [''b'', 2], [''c'', 3]]




def split_and_combine(L):

newL = [ ]

for i in range(len(L)// 2):

newL.append([L [2 * i],L [2 * i + 1] ]])

返回newL


另一种可能性是列表理解:


L = [''a'',1,' 'b'',2,''c'',3]

[[L [i],L [i + 1]],i在范围内(len(L))如果i% 2 == 0]


就个人而言,我认为这只是一个复杂的单一列表

理解应该得到。否则很容易创建

无法维护的代码。


如果你安排事情这么容易(也可能更快)

一开始有两个列表:


zip(['''',''b'',''c''],[1,2], 3])


返回[(''a'',1),(''b'',2),(''c'',3)]


如果你绝对需要将内部元组作为列表,请使用一个列表

理解之后:

[list(t)for t in zip(['''',''b'',''c''],[1,2,3])]

-

史蒂文。



def split_and_combine(L):
newL = []
for i in range(len(L)//2):
newL.append( [L[2*i], L[2*i+1]] )
return newL

Another possibility is a list comprehension:

L = [''a'', 1, ''b'', 2, ''c'', 3]
[[L[i], L[i+1]] for i in range(len(L)) if i%2 == 0]

Personally, I think that''s just about as complex as a single list
comprehension should get. Otherwise it is too easy to create
unmaintainable code.

It is much easier (and probably faster) if you arrange matters so that you
have two lists at the start:

zip( [''a'', ''b'', ''c''], [1, 2, 3] )

returns [(''a'', 1), (''b'', 2), (''c'', 3)]

If you absolutely need the inner tuples to be lists, use a list
comprehension afterwards:
[list(t) for t in zip([''a'', ''b'', ''c''], [1, 2, 3])]
--
Steven.


这篇关于将平面列表转换为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆