【问题标题】:Python is changing datatype from str/float to tuplePython 正在将数据类型从 str/float 更改为 tuple
【发布时间】:2017-09-22 04:25:06
【问题描述】:

我遇到了一个问题,python 中的赋值正在改变数据类型:

代码

# creating list from tuple
newitem = list(item) 
# assignment is done here
m100_productBrand                   = newitem[8],
print "type(item)" , type(item)
print "type(newitem)" , type(newitem)
print "newitem" , newitem
print "newitem[8] : " , newitem[8] , type(newitem[8])
print "m100_productBrand: " , m100_productBrand , type(m100_productBrand)

输出

type(item) <type 'tuple'>
type(newitem) <type 'list'>
newitem ['MOBEFMMWJVUE5ZKB', 'New Model:Good Ear phone', 'A&K G 4040(Black)', 890.0, 890.0, '', 'https://someurl', 10.0, 'A&K', '1', 990.0, 'Mobiles>Handsets', 'https://someurl', 'https://someurl', 'https://someurl', '1', 'Mobile, Battery, Charger, Earphone', '', 'G 4040', 'Black', 'Feature Phones', 'Dual Sim', 2.4, '320 x 480 Pixels', 'HVGA', '', '', '', 32.0, 32.0, 0.0, 0.0, 'Yes', '', '', 'GSM, GSM', '', '', '', 'Yes', '3.5 mm', 'Normal', '', 1050.0, '1 Year Manufacturer Warranty']
    newitem[8] :  A&K <type 'str'>
    m100_productBrand:  ('A&K',) <type 'tuple'>

我很困惑为什么 m100_productBrand 变成元组,即使 newitem[8] 是字符串。

其他信息:

  1. 当我运行相同的代码 python 命令行环境时,它可以工作
    美好的。
  2. 出现这个问题是因为我从元组创建了 newitem 使用列表(项目)?

【问题讨论】:

  • newitem[8], 是一个元组。见逗号。
  • 在某事后加逗号使其成为一个元素的元组。
  • 我通过删除逗号重新运行代码并且它工作正常。谢谢你的帮助。 m100_productBrand = newitem[8] 输出 newitem[8] : A&amp;K &lt;type 'str'&gt; m100_productBrand: A&amp;K &lt;type 'str'&gt;
  • @user2357112 您可以将您的回复添加为答案而不是评论吗?我将其标记为“答案”?

标签: python type-conversion


【解决方案1】:

在 newitem[8] 之后不应出现昏迷

正确的代码是:

# creating list from tuple
newitem = list(item) 
# assignment is done here
m100_productBrand = newitem[8]
print "type(item)" , type(item)
print "type(newitem)" , type(newitem)
print "newitem" , newitem
print "newitem[8] : " , newitem[8] , type(newitem[8])
print "m100_productBrand: " , m100_productBrand , type(m100_productBrand)

【讨论】:

    猜你喜欢
    • 2023-01-28
    • 1970-01-01
    • 2019-12-06
    • 2018-10-01
    • 2023-04-09
    • 2015-01-07
    • 2022-01-06
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多