我试图连接一些列表值中的字符串以添加一些html属性,但是我收到了错误:
无法连接'str'和'float'对象
productlist = ["pedegree","chum", "ColesBrand"]
priceList = [6,5,3]
priceandproduct = []
for x,val in enumerate(productlist):
priceandproduct.extend([productlist[x],priceList[x]])
myhtml = ""
for x in priceandproduct:
myhtml = myhtml + x + "<br/>"
print priceandproduct
我认为这是因为某些元素是float类型,有些是string。所以我尝试将每个元素转换为字符串,然后尝试连接。
for x in priceandproduct:
x = str(x)
这无济于事。
答案 0 :(得分:0)
如果您想要实际修改列表,那将如下所示:
priceandproduct = [ str(x) for x in priceandproduct ]
答案 1 :(得分:0)
如果您更改了这一行怎么办:
priceandproduct.extend([productlist[x], str(priceList[x]]))
那么你的循环可能非常简单:
myhtml = "<br />".join(priceandproduct)
答案 2 :(得分:0)
productlist = ["pedegree","chum", "ColesBrand"]
priceList = [6,5,3]
priceList = [str(x) for x in priceList]
priceandproduct = list(zip(productlist, priceList))
myhtml = ""
for x in priceandproduct:
myhtml += ' '.join(x) + "<br/>"
print(priceandproduct)
print(myhtml)
输出:
[('pedegree', '6'), ('chum', '5'), ('ColesBrand', '3')]
pedegree 6<br/>chum 5<br/>ColesBrand 3<br/>