Reputation: 1032
Hey all. Trying to get a little more efficient with lists in Python but I cant seem to figure out if I can do what I want or even if it is worth figuring out.
stream is a list. Each item in the list is something like :
10,123400FFFE001DB9AA
I am trying to get to the second part of each item after the comma so I run through the list splitting each one and storing it in temp . I them append temp[1) to the other list called incoming_data.
I would like to combine the line that splits and saves to temp and appends to the incoming_data list into one line, something like:
incoming_data.append(item.split(','))
I know the above syntax is totally incorrect but I hope it gets the point across. Here is my current code.
Other critiques welcome as usual. Thanks!
#init the final list
incoming_data = list()
#iterate over each item in the list
for item in stream:
#clear the temp variable for next time
temp = ''
#we sometimes get blank items in the stream list so check first
if item <> '':
#split each item in the stream list using the comma as delimiter
temp = item.split(',')
#append to the final data lis
incoming_data.append(temp[1])
Upvotes: 1
Views: 4712
Reputation: 51817
Actually, you could do incoming_data.append(item.split(',')[1])
. If you really wanted you could combine the whole shebang into a one liner using a list comprehension (mine is now corrected for the blank line thanks to Richard):
incoming_data = [item.split(',')[0] for item in stream if item]
Though if you're actually streaming something you should look at generators(PDF) - they're absolutely amazing.
Upvotes: 1
Reputation: 28110
You can use Python's handy-dandy list comprehensions to do this in one line:
incoming_data = [ item.split(',')[1] for item in stream ]
Upvotes: 1
Reputation: 25491
incoming_data = [item.split(",")[1] for item in stream if item]
The if item
discards the blank lines in stream
.
Upvotes: 5