Howto extract a simple cord from a tuple in python (beginner question)

I have a pretty big tuple that contains:

[('and', 44023), ('cx', 37711), ('is', 36777) .... ] 

I just want to extract the first line, separated by single quotes, so the output for the above tuple would be:

 and cx is 

How to do this (with extensibilty extension to some extent)?

+4
source share
4 answers

Just to provide an alternative way to solve Matthew.

 tuples = [('and', 44023), ('cx', 37711), ('is', 36777) .... ] strings, numbers = zip(*tuples) 

If at some point you decide that you want both parts of the tuple to be in separate sequences (avoids the two concepts of the list).

+4
source
 [tup[0] for tup in mylist] 

This uses list comprehension. You can also use parentheses instead of outer brackets to make this a generator concept, so pricing will be lazy.

+13
source

If you want an accurate conclusion

 and cx is 

Then use list comprehension in conjunction with join strings to join the chararcter of the newline, for example

 yourList = [('and', 44023), ('cx', 37711), ('is', 36777)] print '\n'.join([tup[0] for tup in yourList]) 
+1
source

You can unzip your tuples in a for loop, for example:

 for word, count in mytuple: print "%r is used %i times!" % (word, count) 

You can see that this is widely used in Python docs: http://docs.python.org/tutorial/datastructures.html#looping-technique

0
source

All Articles