1

I'm quite new to python and wondering if I can convert the following for loop in to a one line of code in pythonic way:

w_topic = []
for line in lines: #lines is a list of strings
    word,topic = itemgetter(4,5)(line.split())
    w_topic.append((word,topic))

I have looked at list comprehensions but not sure how to apply it here? it is possible in one line? how do I know if something is doable is one line in the pythonic way?

[(w,t) for w,t in how to fill  here?]
samsamara
  • 4,438
  • 6
  • 34
  • 63

2 Answers2

5
get = operator.itemgetter(4,5)
w_topic = [get(line.split()) for line in lines]
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
  • if `lines` is a generator, representing a big dataset, using parantheses iso backets (making this function call return a generator itself) can help save memory `(get(line.split()) for line in lines)` – Ward Nov 10 '15 at 07:59
2

This is your one line

w_topic.extend([tuple(line.split()[4:6]) for line in lines])

I consider the following as complete code:

lines = ['0 1 2 3 word1 topic1','0 1 2 3 word2 topic2','0 1 2 3 word3 topic3']
w_topic = []

w_topic.extend([tuple(line.split()[4:6]) for line in lines])
print w_topic

result:

[('word1', 'topic1'), ('word2', 'topic2'), ('word3', 'topic3')]

Serjik
  • 9,899
  • 7
  • 60
  • 69