无法解决 Python 中的 TypeError 消息 [英] Unable to solve TypeError message in Python

查看:50
本文介绍了无法解决 Python 中的 TypeError 消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在四处寻找为什么在第 7 行有一个 TypeError 说我的参数在字符串格式化过程中没有转换但有用.

I have been searching around to check why was it that at line 7 there was a TypeError that says that my arguments are not converted during string formatting but to avail.

这里有没有人可以帮助我并让我知道我的代码到底出了什么问题,以便我能够纠正自己.

Is there anybody out here able to help me out and let me know what exactly went wrong with my codes so I am able to correct myself.

以下是我的代码参考.

import sys

even, odd = [], []
count_odd, count_even = 0, 0

for value in sys.argv[1:]:
    if value % 2 == 0:    #TypeError: not all arguments converted during string formatting
        even.append(value)
        total_even = sum(even)
        count_even += 1
    elif value % 2 == 1:
        odd.append(value)
        total_odd = sum(odd)
        count_odd += 1
    else:
        print "Please enter valid integers."

diff = max(sys.argv[1:]) - min(sys.argv[1:])

sys.argv[1:].remove(max(sys.argv[1:]))
sys.argv[1:].remove(min(sys.argv[1:]))
mean = sum(sys.argv[1:])/3

print .......

推荐答案

命令行参数属于 str 类型.

command line arguments are of str type.

在字符串上使用 % 时,您正在调用格式化运算符,并且由于您的字符串不包含任何 %,您会收到此奇怪的消息.

When using % on a string, you're invoking the formatting operator, and since your string doesn't contain any %, you get this weird message.

一旦你知道,修复就很简单:

The fix is simple once you know that:

if int(value) % 2 == 0:

会做的

(请输入有效整数部分不起作用,您必须捕获ValueError以防参数不是整数)

(the please enter valid integers part doesn't work, you have to catch the ValueError in case the argument isn't an integer instead)

当您尝试在参数列表上使用 max 时,您将遇到的下一个奇怪错误.将使用错误的排序(字典序)

Next strange errors you'll have is when you'll try to use max on the list of arguments. Wrong sorting will be used (lexicographical)

最好的方法是事先将您的 arglist 转换为整数,然后处理该列表.

The best way would be to convert your arglist to integers beforehand, and process that list.

让我提出一个独立的例子,它计算奇数 &甚至列表和差异,使用更多的 Pythonic 技术(而且性能也更高,例如:无需在每次迭代时计算数字的总和):

Let me propose a self-contained example which computes odd & even list and diff, using more pythonic techniques (and also more performant, ex: no need to compute the sum of your numbers at each iteration):

import sys

even, odd = [], []

argument_list = ["1","10","24","15","16"]  # sys.argv[1:]

integer_list = [int(x) for x in argument_list]  # let python signal the conversion errors and exit

for value in integer_list:
    # ternary to select which list to append to
    (odd if value % 2 else even).append(value)

total_even = sum(even)
total_odd = sum(odd)
count_even = len(even)  # if you need that
count_odd = len(odd)

diff = max(integer_list) - min(integer_list)

这篇关于无法解决 Python 中的 TypeError 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆