【问题标题】:Changing the type of specific element in a list - python更改列表中特定元素的类型 - python
【发布时间】:2020-03-19 18:50:58
【问题描述】:

作为我代码的一部分,我需要迭代到列表的特定索引(从 csv 文件中获取)并将这些元素的类型从 str 更改为 诠释。但是,当我遍历索引并对其进行转换时,元素不会将其类型更改为 int。

我很困惑为什么以及如何做到这一点?

    def generate_order(bom, parts_cost_filename):

    myfile = open(parts_cost_filename,'r')

    # Retrieving the headers for each of the files part name and the price
    header =  csv.reader(myfile) 

    header_list = []

    for line in header:
        header_list += line
        break

    header_list = list(header_list)
    for number in header_list[1:1]:
        number = int(number)

    print(header_list)


    myfile.close()

【问题讨论】:

  • 请修正帖子中代码的缩进。
  • header_list 已经是您在第 4 行声明的列表,不需要额外的 list() 转换,而且 [1:1] 将是一个空列表
  • [1:1] 将是一个空列表。当你迭代它时,你可能无法用它做任何事情。

标签: python list


【解决方案1】:

我不记得这背后的确切原因,但基本上,你在 for 循环中的 number 变量是不可变的 一个单独的变量而不是内存引用 ,因此如果您为其分配新值,它不会更改原始列表。

您需要通过用方括号对其进行索引来访问列表值。

for index in range(len(some_list)):
    some_list[index] = int(some_list[index])

或者更好的是,使用更 Pythonic 的生成器方法:

some_list = [int(x) for x in some_list]

【讨论】:

  • 这与可变性无关。
  • 这不是可变性。这是因为当你通过 for x in list 循环时,x 是列表项的单独变量,而不是项的内存引用
猜你喜欢
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多