![](/img/trans.png)
[英]How do I convert a Python list of lists of lists into a C array by using ctypes?
[英]How do I convert 3 Lists in a combined array of 3 members in Python?
我是Python 3的新手,我來自Java和javascript。
我怎么去
a = ['a', 'b', 'c']
b = [1, 2, 3]
c = ['red', 'green', 'blue']
至
x = [ ['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue'] ]
以一種簡單的方式,而無需使用一些循環(while / for / map)?
謝謝
這就是內置zip
目的。 zip
接受任意數量的可迭代對象,並返回包含來自相應索引的項的元組。
>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> c = ['red', 'green', 'blue']
>>> list(map(list, zip(a, b, c)))
[['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue']]
zip
生成的元組zip
在這里明確轉換為列表,因為您請求了列表。 如果沒有特別的理由讓列表代替元組,則使用
>>> list(zip(a, b, c))
[('a', 1, 'red'), ('b', 2, 'green'), ('c', 3, 'blue')]
假設所有列表的長度相同,則可以使用列表理解
x = [[a [i],b [i],c [i]]對於范圍(len(a))中的i
這將導致
[['a',1,'紅色'],['b',2,'綠色'],['c',3,'藍色']]
def combine_list(*args):
return map(list, args)
final = list(combine_list(a,b,c))
它將像:
[['a','b','c'],[1、2、3],['紅色','綠色','藍色']]
正如您提到的“以一種簡單的方式,無需使用某些循環(while / for / map)”
這是我能想到的最簡單的方法:
首先,定義包含數據的a,b,c,p,q,r作為臨時列表,並定義一個空列表x以存儲最終輸出。 簡單地使用list的append函數將a,b和c順序附加到x。 打印x,您將獲得列表列表,而無需使用任何for循環! 但是,這將增加額外的內存和鴨子輸入的風險。
a = ['a', 'b', 'c']
b = [1, 2, 3]
c = ['red', 'green', 'blue']
p = []
q = []
r = []
x = []
p.append(a[0])
p.append(b[0])
p.append(c[0])
q.append(a[1])
q.append(b[1])
q.append(c[1])
r.append(a[2])
r.append(b[2])
r.append(c[2])
x.append(p)
x.append(q)
x.append(r)
print(x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.