簡體   English   中英

是否有更多pythonic方法使用列表推導循環多個類似的索引?

[英]Is there a more pythonic way to loop over multiple similar indices using list comprehension?

我有以下代碼

A = [(X(x), Y(y), Z(z)) for x in range(N) for y in range(N) for z in range(N)]

它做我想要的 - 根據我的函數X,Y和Z產生一個代表笛卡爾坐標的元組列表 - 但它不是很漂亮。 我試過了

A = [(X(x), Y(y), Z(z)) for x, y, z in range(N)]

但那沒用。 是否有更優雅和pythonic的方式來做到這一點?

from itertools import product
A = [(X(x), Y(y), Z(z)) for x, y, z in product(range(N), repeat=3)]

你可以這樣做:

import itertools

res = [X(each[0]), Y(each[1]), Z(each[2]) for each in itertools.combinations(N, 3)]

這將為您提供所有獨特的組合。 你可以在這里找到更多相關信息。

繼續編碼:)

由於x,y和z具有相同的值,您可以這樣做:

A = [(X(x), Y(x), Z(x)) for x, in range(N)]

您還可以使用地圖功能:

f = lambda x : (X(x), Y(x), Z(x))
map(f, range(N))

祝好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM