Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2017 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/db68269de025fc3b31b076001e20a599 to your computer and use it in GitHub Desktop.
Save anonymous/db68269de025fc3b31b076001e20a599 to your computer and use it in GitHub Desktop.

感覺你只是被你自己的變數命名搞混了。

先不講細節,list comprehension 跟使用 for-loop 來產生 list 的結果會是一樣的 (事實上前者是產生一個 generator,後者不是,不過入門的話先不用考慮這個):

a = [x * x for x in range(10)]

是等價於

a = []
for x in range(10):
    a.append(x * x)

如果你要暫存 x * x 的值,那是寫成

a = []
for x in range(10):
    temp = x * x # 注意變數名稱不是 a, a 是結果
    a.append(temp)

所以你貼文裡的

abc = [x*x for x in range(10)]
efg = [y*abc for y in range(10)]

是等價

abc = []
for x in range(10):
   abc.append(x * x)
efg = []
for y in range(10):
    efg.append(y * abc)

結果會一樣的。


另外,因為排版的關係,我不確定你程式是想做什麼。 但上面的程式中的 y * abc 因為 y 是 int, abc 是 list,這代表將 abc 重覆 y 遍, 例如 [1, 2, 3] * 2 得到 [1, 2, 3, 1, 2, 3],我個人很少使用到這個東西。 我猜你可能是想寫雙迴圈,底下給出一個使用雙迴圈的例子:九九乘法

res = ['{} . {} = {}'.format(x, y, x * y) for x in range(10) for y in range(10)]

等價於

res = []
for x in range(10):
    for y in range(10):
        res.append('{} . {} = {}'.format(x, y, x * y))

如果這不是你要的,建議你把 code 先貼到 gist 或 codepad 或 ideone,再把網址貼過來。 要不然還是會一樣,排版被 FB 吃掉,我不太懂你是想做什麼。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment