【问题标题】:How to change a list item from a string to a float in Python3如何在 Python3 中将列表项从字符串更改为浮点数
【发布时间】:2013-09-11 02:21:30
【问题描述】:
list=['word','2']

print(type(list[0]))

<class 'str'>

print(type(list[0]))

<class 'str'>

我希望 list[0] 保持为字符串,而 list[1] 变为浮点数。

对不起,如果我没有以正确的格式发布此内容,我不知道该怎么做。

【问题讨论】:

    标签: list types python-3.x tuples


    【解决方案1】:

    您将不得不重新分配元素:

    list[1] = float(list[1])
    

    【讨论】:

      【解决方案2】:

      你需要这样的东西:

      list[1] = float(list[1])
      

      如以下成绩单所示:

      >>> list=['word','2']
      
      >>> type(list[0]) ; type(list[1])
      <type 'str'>
      <type 'str'>
      
      >>> list ; list[1] = float(list[1]) ; list
      ['word', '2']
      ['word', 2.0]
      
      >>> type(list[0]) ; type(list[1])
      <type 'str'>
      <type 'float'>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 2019-03-31
        相关资源
        最近更新 更多