Home > OS >  Save a list as txt file with comma and remove duplicates
Save a list as txt file with comma and remove duplicates

Time:10-19

How can I save the following list to a txt file.

col_list = [['AAPL'], ['AMZN'], ['COP'], ['COP'], ['COP']]

output.txt should be: AAPL,AMZN,COP

CodePudding user response:

First, you have to convert every element of col_list into a string

col_list = [['AAPL'], ['AMZN'], ['COP'], ['COP'], ['COP']]
new_list = list(col_list[i][0] for i in range(len(col_list)))
# ['AAPL', 'AMZN', 'COP', 'COP', 'COP']

Second, remove the duplicate value with set and list

new_list1 = list(set(new_list)) # ['AMZN', 'AAPL', 'COP']

Then you write each element of the final list into a file, with the comma after, except the last element

with open('output.txt', 'w ') as f:
    i = 0
    while i < len(new_list1)-1:
        f.write(new_list1[i])
        f.write(',')
        i = i 1
    f.write(new_list1[-1])
#AMZN,AAPL,COP

If each element of the first list has multiplier values, like col_list = [['AAPL, 'AAA'], ['AMZN'], ['COP', 'ZZZZ']]. You could extract the string with two loops, 1 loop running through each ele in the outside list and 1 loop through each ele in the inside list

CodePudding user response:

First, you need to flatten your input list,

In [1]: [j for i in col_list for j in i]
Out[1]: ['AAPL', 'AMZN', 'COP', 'COP', 'COP']

Then remove the duplicates using set and write them into a file. The code will look like this,

col_set = set([j for i in col_list for j in i])
with open('Output.txt', 'w') as fp:
    fp.write(','.join(col_set))
  • Related