python - Can I use %f and %d to format floats and ints to strings in a list? -
i starter python ,without programming experience , here's question
i have list called n
n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ]
and want create list 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 like
for in range(len(n)): k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1]
but got typeerror : unsupported operand type(s) % : 'nonetype' , 'float'
i'm not sure if asked question in proper way but...hope can me this, thx t^t
the numbers floats , ints, respectively. expected k
looks converts them strings. can build way list comprehension:
>>> n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ] >>> k = [ (str(x) , {'num': str(y)}) 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 code trying:
for in range(len(n)):
- not way iterate in python. don't need item index reference item in current iteration. example:
>>> item in n: ... print item ... (1.1, 5) (2.4, 7) (5.4, 6) (9.8, 14) (10, 4) >>> >>> # let's each part of tuple separately: ... 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 @ part:
k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1]
- looks trying %
substitution in print '%s world!' % 'hello'
=> hello world!
. work, need use % operator after string, so:
>>> k = [] >>> 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 %
format stuff, cast floats , ints strings, using str()
. adapting version these here:
>>> k = [] >>> item in n: ... k.append((str(item[0]), {'num': str(item[1])})) ...
and since know item
refers each element in list, , each tuple, can expand in iterator-variables, x
, y
used here:
>>> k = [] >>> x, y in n: ... print 'index 0:', x, '; index 1', y ... k.append((str(x), {'num': str(y)})) ...
lastly, pattern of creating empty list k
, appending items in loop can done in more pythonic way in list comprehensions:
>>> k = [(str(x), {'num': str(y)}) x, y in n]
(note k
does not first need initialised empty list.)
Comments
Post a Comment