简体   繁体   English

将字符串转换为整数Python

[英]Converting string to integer Python

I am trying to count the number of 0's, positives, negative numbers in array. 我试图计算数组中0,正数,负数的数量。 I have explicitly converted every string to integer here: 我在这里明确地将每个字符串转换为整数:

k = []
n = int(raw_input())
p=neg=z=0
p = int(p)
neg = int(neg)
z = int(z)

for i in range (0,n):
    numb = int(raw_input("numb: "))
    if numb==0:
        z +=1
    if numb<0:
        neg+=1
    if numb>0:
        p +=1
    k.append(numb)

print "Array: ", k
print '%.5f' %z/n
print '%.5f' % neg/n
print '%.5f' %p/n

It keeps giving me this error: unsupported operand type(s) for /: 'str' and 'int'. 它一直给我这个错误:/:'str'和'int'的不支持的操作数类型。

You need to add parens: 你需要添加parens:

print "Array: ", k
print '%.5f' % (z / n)
print '%.5f' % (neg / n)
print '%.5f' % (p / n)

The format is being done first so you end up trying to / the result which is a string by an int. 格式正在首先完成,所以你最终尝试/结果是int的字符串。 The parens will mean the division etc.. is done and the result is formatted. parens意味着分裂等...完成并且结果被格式化。

You might find using str.format less error prone: 您可能会发现使用str.format不易出错:

print '{:.5f}'.format(z / n)

Also unless you want the division to floor you should cast to float not int: 另外,除非你想将分区放到地板上,否则你应该转换为float而不是int:

n = float(raw_input())

Quoting official documentation : 引用官方文件

The following table summarizes the operator precedences in Python, from lowest precedence (least binding) to highest precedence (most binding). 下表总结了Python中的运算符优先级,从最低优先级(最小绑定)到最高优先级(大多数绑定)。 Operators in the same box have the same precedence. 同一个框中的运算符具有相同的优先级。 Unless the syntax is explicitly given, operators are binary. 除非明确给出语法,否则运算符是二进制的。 Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left). 同一个框组中的操作符从左到右(除了比较,包括测试,它们都具有相同的优先级和从左到右的链 - 参见比较 - 和取幂,从右到左分组)。

While studying table we can see row: 在学习表时我们可以看到行:

*, /, //, % Multiplication, division, remainder [8]

Footnote [8] says: 脚注[8]说:

The % operator is also used for string formatting; %运算符也用于字符串格式化; the same precedence applies. 同样的优先权适用。

Both % and / operators has same precedence. %/运算符具有相同的优先级。 Therefore - they are evaluated in standard order. 因此 - 它们按标准顺序进行评估。 Following equality holds: 平等之后:

'%.5f' %z/n == (`%.5f` % z) / n

To change evaluation precedence you need to use parentheses. 要更改评估优先级,您需要使用括号。

'%.5f' % (z/n)  # It would format string with a result of z/n operation.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM