我是 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'
我不确定我是否以正确的方式问了这个问题,但是...希望有人能帮助我解决这个问题,thx T^T
最佳答案
数字已经分别是 float 和整数。您期望的 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'})]
>>>
Wrt 你正在尝试的代码:
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 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()
将 float 和整数转换为字符串即可。因此,请在此处调整您的版本:
>>> 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
不需要首先需要初始化为一个空列表。)
关于python - 我可以使用 %f 和 %d 将 float 和整数格式化为列表中的字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327803/