我是python的入门者,没有任何编程经验,这是我的问题
我有一个叫n的清单
n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ]
我想创建一个看起来像
k = [ ('1.1' , {'num' : '5'}) ,
('2.4' , {'num' : '7'}) ,
('5.4' , {'num' : '6'}) ,
('9.8' , {'num' : '14'}) ,
('10' , {'num' : '4'})
]
我已经尝试过类似的东西
for i in range(len(n)):
k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1]
但是我有一个 TypeError : unsupported operand type(s) for % : 'NoneType' and 'float'
我不确定我是否以适当的方式提出了这个问题,但是...希望有人可以帮我解决这个问题,例如T ^ T
这些数字已经分别是浮点数和整数。您所期望的k
看起来像将它们转换为字符串。因此,您可以通过列表理解来构建它:
>>> 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'})]
>>>
写出您正在尝试的代码:
for i in range(len(n)):
-这不是在Python中进行迭代的好方法。您实际上并不需要项目索引来引用当前迭代中的项目。例如:
>>> 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
现在看一下该部分:
k.append(('%f', {'num' : '%d'})) % n[i][0] % n[i][1]
-好像您正在尝试进行=>中的%
替换。为此,您需要在字符串后立即使用%运算符,如下所示:print '%s world!' % 'hello'
hello world!
>>> 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'}
)]
现在,不用做%
格式化工作,只需使用即可将浮点数和整数转换为字符串str()
。因此,请在此处修改您的版本:
>>> k = []
>>> for item in n:
... k.append((str(item[0]), {'num': str(item[1])}))
...
既然你知道item
是指在列表中的每个元素,而且每个始终是一个元组,你可以扩展它的迭代变量,比如x
和y
这里使用:
>>> k = []
>>> for x, y in n:
... print 'index 0:', x, '; index 1', y
... k.append((str(x), {'num': str(y)}))
...
最后,创建空列表k
然后在循环中向其添加项目的模式可以通过列表理解的一种更加Python化的方式来完成:
>>> k = [(str(x), {'num': str(y)}) for x, y in n]
(请注意,k
不需要首先将其初始化为空列表。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句