【问题标题】:How Can I Convert of String To Integer Value in a List in Python?如何在 Python 的列表中将字符串转换为整数值?
【发布时间】:2020-09-18 07:40:20
【问题描述】:

这是我为我的项目所做的代码,它从 csv 文件中获取值。我收到一个错误,将 csv 文件中的数据 u= 作为字符串而不是整数。如何将其转换为整数值或浮点值?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)

proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper[order_id] = country
print(proper)

def get_hash(key):
    hash = 0
    for i in range(key):
        hash += 1
    return hash % 100000
get_hash('8469376') 

这是我得到的错误 TypeError: 'str' object cannot be interpreted as an integer

【问题讨论】:

  • 发布完整的回溯,以便我们查看导致错误的行?
  • 必须是get_hash(8469376) 而不是get_hash('8469376')

标签: python pandas list csv hash


【解决方案1】:

int 类有两个参数int(str, base=)。并且不要使用hash 作为变量 它是 python 中的一个函数,所以作为一个规则,“永远不要将函数用作变量”

试试:

def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100000
get_hash('8469376') 

【讨论】:

  • 非常感谢!现在从您发送的代码中解决了。再次感谢!
【解决方案2】:

变化:

get_hash('8469376') 

收件人:

get_hash(8469376) 

由于get_hash 函数的关键参数被传递给range 函数,它必须是int 类型(而不是像你做的那样是字符串)。

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2017-07-30
    • 2011-09-16
    • 2020-10-09
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多