gogasca
gogasca

Reputation: 10058

Pythonic way to add elements csv.writerows

I have a list of lists. Each list should have 6 elements. There are cases in which my list only contains 1 element (Check last element of following list):

[['lemonade', '/g/11bz0dg4b_', '46.6522598267', 'Lemonade', 'Beyonc\xc3\xa9', 'en'], 
 ['blank space', '/m/012d3qyr', '153.392837524', 'Blank Space', '', 'en'],
 ['radiolab', '/g/11b80zm_6d', '11.685131073', 'Radiolab', '', 'en'], 
 ['migos t shirt']]

Hence I can easily do this and then append:

l = ['migos t shirt'] 
l += ['','','','','']
ll.append(l)

Is there a better/elegant way to do this? End goal is to use my list of lists with csv.writerows and want my file to have a consistent number of commas in this case 6 elements.

Upvotes: 1

Views: 54

Answers (2)

Mike Müller
Mike Müller

Reputation: 85492

You can multiply a list with an empty string [''] to get a list with as many empty strings:

>>>  [''] * 3
['', '', '']

Multiplying by zero gives you an empty list:

>>>  [''] * 0
[]

Find out the difference of your desired size (6) and the current length of the list with len(line) and add a list with as many '' to end of each line:

For this data:

data = [['lemonade', '/g/11bz0dg4b_', '46.6522598267', 'Lemonade', 'Beyonc\xc3\xa9', 'en'],
        ['blank space', '/m/012d3qyr', '153.392837524', 'Blank Space', '', 'en'],
        ['radiolab', '/g/11b80zm_6d', '11.685131073', 'Radiolab', '', 'en'],
        ['migos t shirt']]

you can apply these:

size = 6
for line in data:
    line += [''] * (size - len(line))

to get this result:

[['lemonade', '/g/11bz0dg4b_', '46.6522598267', 'Lemonade', 'Beyoncé', 'en'],
 ['blank space', '/m/012d3qyr', '153.392837524', 'Blank Space', '', 'en'],
 ['radiolab', '/g/11b80zm_6d', '11.685131073', 'Radiolab', '', 'en'],
 ['migos t shirt', '', '', '', '', '']]

This approach modifies the list compared to a list comprehension that creates an entirely new list. This can be really useful for large lists. Further more, if all lines are already 6 elements long, there won't be any changes to the original list. A list comprehension would create a new list even if the original list is already in perfect shape. i.e. has 6 elements in all sub list.

Upvotes: 5

Po Stevanus Andrianta
Po Stevanus Andrianta

Reputation: 712

try this

ll = list(map(lambda x: x if len(x)==6 else x + ['']*(6-len(x)), ll))

insipred by @Mike Müller`s answer

ll = list(map(lambda x: x + ['']*(6-len(x)), ll))

with list comprehension

ll2 = [x + ['']*(6-len(x)) for x in ll]

Upvotes: 4

Related Questions