為什么當(dāng)我在第 4 行中放入方括號(hào)時(shí)輸出發(fā)生變化?def x(a, b): d = [] for i in range(0, a): d += str(i) + b return dc = x(3, "7")print(c)輸出:['0', '7', '1', '7', '2', '7']def x(a, b): d = [] for i in range(0, a): d += [str(i) + b] return dc = x(3, "7")print(c)輸出:['07', '17', '27']為什么輸出會(huì)這樣改變?
1 回答

肥皂起泡泡
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
這很簡(jiǎn)單,
d += 'a' + 'b' # is same as [] + list('ab') = ['a', 'b']
相似地
d += ['a' + 'b'] # is same as [] + ['ab'] = ['ab']
當(dāng)您鍵入將字符串轉(zhuǎn)換為列表時(shí),它會(huì)創(chuàng)建一個(gè)包含單個(gè)字符的列表作為列表的元素。
例如:
a = "Good" b = list(a) print(b) # will print as --> ['G', 'o', 'o', 'd']
添加回答
舉報(bào)
0/150
提交
取消