Inserting data into a nested list in Python
I have a list like this:
list = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]
I am trying to return a list like this where ' newdata' is added into every row in the seco开发者_JS百科nd "column":
list = [['a1', 'a2 newdata', 'a3'], ['b1', 'b2 newdata', 'b3'], ['c1', 'c2 newdata', 'c3']]
What is best way to do this?
Considering ' newdata' is a string, else you ll have to use str()
for item in list:
item[1] += ' newdata'
To iterate over your list you can do something like this:
for element in my_list:
print element
And it will print all the elements in your list. It appears that every element inside your nested list is a string, therefore, to add a string to the 2nd element of that nested list you'd need to:
for element in my_list:
print element[1] += ' newdata'
Remember, index starts at 0. if 'newdata' isn't a string you'll need to use this as:
for element in my_list:
print element[1] += ' ' + str(newdata)
This page might have more useful information on how to iterate over your list:
- https://wiki.python.org/moin/ForLoop
精彩评论