我有一个示例数据,例如:
[[[['D', 'X'], 'True', '7.6S', '12', '12', '-1', 'False', '1239217113'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']],
[[['D', 'X3'], 'True', '30.6S', '12', '12', '-1', 'False', '2080709342'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']]]
其列表由较小的列表和字符串组成。
我想将其打印到一个文件:
D,X,True,7.6S,12,12,-1,False,1239217113,12,6.1D,6.2D,6.3D,6.4D
是否有内置函数可以执行此操作?有什么聪明的方法可以做到这一点?
答案 0 :(得分:2)
使用生成器:
l = [[[['D', 'X'], 'True', '7.6S', '12', '12', '-1', 'False', '1239217113'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']],[[['D', 'X3'], 'True', '30.6S', '12', '12', '-1', 'False', '2080709342'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']]]
def flatten(l):
for e in l:
if isinstance(e, list):
yield from flatten(e)
else:
yield e
with open('test.txt', 'w') as f:
print(','.join(flatten(l)), file=f)
答案 1 :(得分:1)
data=[[[['D', 'X'], 'True', '7.6S', '12', '12', '-1', 'False', '1239217113'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']],[[['D', 'X3'], 'True', '30.6S', '12', '12', '-1', 'False', '2080709342'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']]]
f={ list: lambda x: x, str: lambda x: [x] }
while True:
data2 = sum( map(lambda y: f[type(y)](y), data ), [] )
if data2 == data:
break
data = data2
print(data)
答案 2 :(得分:0)
非常简单。
lists = [[['D', 'X3'], 'True', '30.6S', '12', '12', '-1', 'False', '2080709342'], '12', ['6.1D', '6.2D', '6.3D', '6.4D']]
str_list = str(lists)
result = str_list.replace('[','').replace(']','')
with open('name.txt','w') as FILE:
FILE.write(result)
答案 3 :(得分:0)
def print_all_elements(big_list):
for i in big_list:
if isinstance(i, list):
# print(i)
print_all_elements(i)
else:
print(i)
print_all_elements([[[['D', 'X'], 'True', '7.6S', '12', '12', '-1', 'False', '1239217113'],
'12', ['6.1D', '6.2D', '6.3D', '6.4D']],
[[['D', 'X3'], 'True', '30.6S', '12', '12', '-1', 'False', '2080709342'],
'12', ['6.1D', '6.2D', '6.3D', '6.4D']]])