列表:
results = [['04-25', [1, 2, 3, 4]], ['04-26', [5, 6, 7, 8]], ['04-27', [9, 20, 11, 21]]
尝试获取此输出:
[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]
我已经尝试过了:
data = [a for b in [_ for _ in results[i]] for a in b]
将列表中的每个字符分成一个不同的元素,如下所示:
['0', '4', '-', '2', '5', 1, 2, 3, 4]
如何仅访问内部列表并使其扁平化?
答案 0 :(得分:7)
results = [['04-25', [1, 2, 3, 4]], ['04-26', [5, 6, 7, 8]], ['04-27', [9, 20, 11, 21]]]
data = [[a, *b] for a,b in results]
print(data)
输出:
[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]
答案 1 :(得分:4)
您可以添加第一个值和内部list
:
[[i] + j for i, j in results]
输出:
[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]
答案 2 :(得分:0)
尝试此代码!
results = [['04-25', [1, 2, 3, 4]], ['04-26', [5, 6, 7, 8]], ['04-27', [9, 20, 11, 21]]]
for i in range(0,len(results)):
temp = []
temp.append(results[i][0])
for j in range(0,len(results[i][1])):
temp.append(results[i][1][j])
results[i] = temp
print(results)
输出:
[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]
答案 3 :(得分:0)
使用extend
和append
new_list = []
for item in results:
new_sublist = []
for sub_item in item:
if isinstance(sub_item, list):
new_sublist.extend(sub_item)
else:
new_sublist.append(sub_item)
new_list.append(new_sublist)
print(new_list)
输出:[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]