Xiadan Xiadan - 4 months ago 14
Python Question

Can I use %f, %d to generate a list?

I am a starter with python ,without any programming experience
and here's my question

I have a list called n

n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ]


and I want to create a list which looks like

k = [ ('1.1' , {'num' : '5'}) ,
('2.4' , {'num' : '7'}) ,
('5.4' , {'num' : '6'}) ,
('9.8' , {'num' : '14'}) ,
('10' , {'num' : '4'})
]


I've tried something like

for i in range(len(n)):
k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1]


but I got a
TypeError : unsupported operand type(s) for % : 'NoneType' and 'float'


I'm not sure if I asked this question in a proper way but...hope someone can help me with this, thx T^T

Answer

The numbers are already floats and ints, respectively. Your expected k looks like it converts them to strings. So you can build it that way with a list comprehension:

>>> n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ]
>>> k = [ (str(x) , {'num': str(y)}) for x, y in n]
>>> k
[('1.1', {'num': '5'}), ('2.4', {'num': '7'}), ('5.4', {'num': '6'}), ('9.8', {'num': '14'}), ('10', {'num': '4'})]
>>>

Wrt the code you were trying:

for i in range(len(n)): - this is not a good way to iterate in Python. You don't actually need the item index to reference the item in the current iteration. For example:

>>> for item in n:
...   print item
...
(1.1, 5)
(2.4, 7)
(5.4, 6)
(9.8, 14)
(10, 4)
>>>
>>> # let's get each part of the tuple separately:
... for item in n:
...   print 'tuple index 0:', item[0],
...   print 'tuple index 1:', item[1]
...
tuple index 0: 1.1 tuple index 1: 5
tuple index 0: 2.4 tuple index 1: 7
tuple index 0: 5.4 tuple index 1: 6
tuple index 0: 9.8 tuple index 1: 14
tuple index 0: 10 tuple index 1: 4

Now take a look at the part:
k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1] - looks like you were trying to do the % substitution like in print '%s world!' % 'hello' => hello world!. For that to work, you need to use the % operator immediately after the string, like so:

>>> k = []
>>> for item in n:
...   k.append(('%f' % item[0], {'num': '%d' % item[1]}))
...
>>> k
[('1.100000', {'num': '5'}), ('2.400000', {'num': '7'}), ('5.400000', {'num': '6'}), ('9.800000', {'num': '14'}), ('10.000000', {'num': '4'}
)]

Now, instead of doing the % format stuff, just cast your floats and ints to strings, using str(). So adapting your version with these here:

>>> for item in n:
...   k.append((str(item[0]), {'num': str(item[1])}))
...
>>>
Comments