如何在Python的列表中将字符串转换为整数值?

问题描述 投票:0回答:1

这是我为项目执行的代码,它从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

python pandas list csv hash
1个回答
0
投票

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') 
© www.soinside.com 2019 - 2024. All rights reserved.