Python 3 int()函数未将输入字符串转换为整数 [英] Python 3 int() function is not converting input string to integer
问题描述
我正在研究一个从CSV文件读取数据的小程序.作为程序的一部分,用户输入仅用于选择> =的数据,但是在运行代码时出现 TypeError:不可排序的类型:str()> = int().看起来刺痛没有转换成整数.
I am working on a small program that reads data from a CSV file. As part of the program, user input is used to only select data that >= but I get TypeError: unorderable types: str() >= int() when I run the code. Looks like the sting is not converting to integer.
def get_csv_data(data_type, num):
import csv
ga_session_data = {}
ga_pageviews_data = {}
with open('files/data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
page, sessions, pageviews = row
ga_session_data[page] = int(sessions)
ga_pageviews_data[page] = int(pageviews)
if data_type == 'sessions' and sessions >= int(num):
for page, sessions in ga_session_data.items():
print(page, ' - ', sessions)
elif data_type == 'pageviews' and pageviews >= int(num):
for page, pageviews in ga_pageviews_data.items():
print(page, ' - ', pageviews)
def main():
while(True):
question = input("Are you interested in sessions or pageviews?")
if question == 'sessions':
number = int(input("What range are you interested in?"))
get_csv_data(data_type = 'sessions', num = int(number))
elif question == 'pageviews':
number = input("What range are you interested in?")
get_csv_data(data_type = 'pageviews', num = int(number))
else:
print("Invalid Input. Choose between sessions and pageviews.")
main()
推荐答案
int
不会将其参数 cast 转换为就地整数.实际上,这些参数是不可变的.
int
does not cast its parameters to integer in-place. In fact those parameters are immutable.
int(sessions)
不能精确地做您认为做的事情. session
未被修改,但是该调用的返回值是int
.
int(sessions)
does not exactly do what you think it does. session
is not modified, but the return value of that call is an int
.
您应该将返回的值分配给新名称/相同名称:
You should assign the returned value to a new/same name:
sessions = int(sessions)
pageviews = int(pageviews)
运算符>=
现在可以比较您拥有的两个变量,因为它们现在都是整数.
The operator >=
can now compare the two variables you have, since they are now both integers.
您可能还想这样重写if
块:
You may also want to rewrite that if
block like so:
if data_type == 'sessions':
for page, sessions in ga_session_data.items():
if sessions >= int(num):
print(page, ' - ', sessions)
通过这种方式,您实际上是在检查字典中的会话计数,而不是for循环中的会话.
In this way, you're actually checking the sessions count in the dictionary and not the sessions from the for loop.
这篇关于Python 3 int()函数未将输入字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!