list = [1, 'one', 'first', 2, 'two', 'second', 3, 'three', 'third', 4, 'four', 'fourth', 5, 'five', 'fifth', 6, 'six', 'sixth']
制作這樣的新串列是一種緊湊的方式嗎?(合并 3 個元素,然后再合并 3 個……):
['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']
uj5u.com熱心網友回復:
使用串列推導轉換為字串和join:
N = 3
out = [''.join(map(str, lst[i:i N])) for i in range(0, len(lst), N)]
輸出:
['1onefirst',
'2twosecond',
'3threethird',
'4fourfourth',
'5fivefifth',
'6sixsixth']
uj5u.com熱心網友回復:
為此,您可能希望在 Python 中結合使用串列推導和切片:
# Defining the input list
input_list = [
1, "one", "first",
2, "two", "second",
3, "three", "third",
4, "four", "fourth",
5, "five", "fifth",
6, "six", "sixth"
]
# Using slices of the input in a list comprehension
list_merge_every_third = [
''.join(str(e) for e in input_list[i * 3 : i * 3 3])
for i in range(len(input_list) // 3)
]
注意:您可能首先要測驗輸入串列長度是否為 3 的倍數。
我也建議不要使用符號“list”來指定你的輸入,因為它是 Python 語言的保留關鍵字來指定串列型別。
uj5u.com熱心網友回復:
我希望以下解決方案是您正在尋找的。
list = [1, "one", "first", 2, "two", "second", 3, "three", "third",
4, "four", "fourth", 5, "five", "fifth", 6, "six", "sixth"]
def merge_list(list, n):
temp_list = [list[i:i n] for i in range(0, len(list), n)]
return [''. join(str(i) for i in temp_list) for temp_list in temp_list]
list_merge_every_third = merge_list(list, 3)
print(list_merge_every_third)
結果串列如下所示:
['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fififth', '6sixsixth']
uj5u.com熱心網友回復:
您還可以使用生成器來回傳組合的三元組,如下所示:
input_list = [
1, "one", "first",
2, "two", "second",
3, "three", "third",
4, "four", "fourth",
5, "five", "fifth",
6, "six", "sixth"
]
def triples(_list):
for i in range(0, len(_list), 3):
yield ''.join(map(str, _list[i:i 3]))
print([triple for triple in triples(input_list)])
輸出:
['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515071.html
標籤:Python列表加入合并
上一篇:內部連接??2個表的問題
