简体   繁体   中英

How to print a list of lists as a simple string?

I have a sample data like :

[[[['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']]]

Its list comprising of smaller lists and strings .

I want to print it to a file like :

D,X,True,7.6S,12,12,-1,False,1239217113,12,6.1D,6.2D,6.3D,6.4D

Is there any built in function to do this ? any smart way to achieve this ?

Using generator :

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)
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)

Its very easy.

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)
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']]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM