3

I get back good results from the following, but how to I extract that data from the tuple? In other words, how do I clean up the data?

Here is the data from the database, I ran out.

>>> policy_id = ((2309L,), (118L,), (94L,))
>>> for i in policy_id:
        print i


(2309L,)
(118L,)
(94L,)

But I want the result as:

2309
118
94
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
a1my
  • 75
  • 1
  • 1
  • 5
  • 1
    with the answers given below you should be able to figure out how to do your "next i want the result is" – gefei May 11 '12 at 10:42

6 Answers6

11
policy_id = ((2309L,), (118L,), (94L,))
for i in policy_id:
    print i[0]  
Maria Zverina
  • 10,863
  • 3
  • 44
  • 61
3
>>> from itertools import chain
>>> policy_id = ((2309L,), (118L,), (94L,))
>>> for i in chain.from_iterable(policy_id):
        print i


2309
118
94
jamylak
  • 128,818
  • 30
  • 231
  • 230
2
print '\n'.join(str(x[0]) for x in policy_id)
gefei
  • 18,922
  • 9
  • 50
  • 67
2

A notion that I like, that might confuse to begin with, is the following:

Python2

policy_id = ((2309L,), (118L,), (94L,))
for i, in policy_id:
    print i

Python3

policy_id = ((2309,), (118,), (94,))
for i, in policy_id:
    print(i)

The , after the i unpacks the element of a single-element tuple (does not work for tuples with more elements than one).

AndreasHassing
  • 687
  • 4
  • 19
1
>>> policy_id = ((2309L,), (118L,), (94L,))
>>> print("\n".join(str(x[0]) for x in policy_id))
2309
118
94
jamylak
  • 128,818
  • 30
  • 231
  • 230
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Other way using map

map(lambda x: str(x[0]), policy_id)

If you want new lines then

"\n".join(map(lambda x: str(x[0]), policy_id))

Mirage
  • 30,868
  • 62
  • 166
  • 261