3
I would like to have two lists: one with the name of the fruit and the other with the colors.
lista = ['banana [amarela]\n', 'uva [vinho]\n', 'laranja [laranjado]\n', 'kiwi [verde]\n', 'framboesa [vermelho]\n', 'coco [marrom]\n']
lines = lista.split(" ")
fruits = []
colors = []
for line in lines:
fruits.append(line[0])
#colors.append(line[1]) #IndexError: string index out of range
print(fruits)
#print(colors) #IndexError: string index out of range
Script output:
['[', "'", 'b', 'a', 'n', 'a', 'a', 'n', 'a', '' '[', 'a', ’m', 'a', 'r', 'r', 'l', 'a', ']', '' ', 'n', "'"', ',' ', ''' ', 'u', 'v', 'i', 'n', 'h', 'o', ']', ', 'n', "'"'"', ',' ', 'a', 'a', 'n', 'j', a', ', 'a', ', 'a', ', 'a', ', 'a', ', 'a', ', 'a', ', ', 'a', 'a', ', 'a'[', 'l', 'a', 'r', 'a', 'n', 'j', 'a', '’d', 'o', '']', '''', 'n', "', ',' ', '"', 'k', 'i', 'w', 'i', '' ', 'i', ', '['v', 'e', '’d', 'e', ']', ', ''''', '"''''"''"', 'r', 'a', 'b', 'o', 'e', ', ', 'a', ', ', ''', ''[', ''', '''''', ''''', ''', ''''''[, 'v', ', 'r', ', ', ', ', ''', ''''', ', ', '', ', '''', ', ''', ', ', '', '''', ', ' "'", ',', ', '' ', '"'", 'c', 'o', 'c', 'o', '' ', '[', ’m', 'a', 'r', 'r', 'o', ’m', ']', ', ', 'n', "'", ']']
Desired exit:
Fruits = ['banana', 'grape', 'orange', 'kiwi', 'raspberry', 'coconut']
Colors = ['yellow', 'wine', 'orange', 'green', 'red', 'brown']
Are these values in a file? You are using the functions there
read
andreadlines
which appear to be a text file.– Woss
Oh yes, sorry. I am using these values in a file but I thought it would be easier to put the list here. I will edit my answer.
– pitanga
But in what format is each line in the file ? There is always only one fruit and one color per line ?
– Isac
It gets easier, in fact, I just wanted to make sure I wasn’t using the functions inappropriately to read the values of a list.
– Woss
Isac, exactly. One fruit and one color per line
– pitanga