iT邦幫忙

0

python list和for的問題

想請教一下下面的問題,我現在有下面3個list

kkk = []
ttt = [111,222,333]
yyy = [1,4,8]

我想要把他append到kkk裡面,讓kkk變成

[111,222,222,222,222,333,333,333,333,333,333,333,333]

這樣該怎麼去寫for迴圈呢?

2
hokou
iT邦新手 1 級 ‧ 2021-10-12 08:50:33
最佳解答

假設 yyy 的長度是跟著 ttt 的話

kkk = []
ttt = [111,222,333]
yyy = [1,4,8]

for i in range(len(ttt)):
    for j in range(yyy[i]):
        kkk.append(ttt[i])

print(kkk)
# [111, 222, 222, 222, 222, 333, 333, 333, 333, 333, 333, 333, 333]
0
DanSnow
iT邦研究生 4 級 ‧ 2021-10-12 00:29:17

如果說沒有一定要直接去修改 kkk 的陣列的話:

import itertools

kkk = list(itertools.chain.from_iterable(itertools.repeat(n, count) for n, count in zip(ttt, yyy)))
0
math2021
iT邦新手 5 級 ‧ 2021-10-13 02:12:25

https://ithelp.ithome.com.tw/upload/images/20211013/20138419lxsxEckSdF.png

1
jiatool
iT邦新手 4 級 ‧ 2021-10-13 08:38:28

也可以使用 zip

kkk = []
ttt = [111, 222, 333]
yyy = [1, 4, 8]

for t, y in zip(ttt, yyy):
    kkk.extend([t] * y)

print(kkk)
# [111, 222, 222, 222, 222, 333, 333, 333, 333, 333, 333, 333, 333]

我要發表回答

立即登入回答