python TypeError 使用 sys.stdout.write 作为数组元素值

python TypeError using sys.stdout.write for array element values

我在 Python 中有一个打印语句,显示数组中元素的值和长度。 然后我需要使用 sys.stdout.write 而不是打印来做同样的事情,但是我收到以下错误。

使用print的原代码:

import sys
words = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
for w in words:
    print(w, len(w))

用 sys.stdout.write 替换打印:

import sys
countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
for w in countries:
    sys.stdout.write(countries[w]+" "+len(countries[w]))

我得到的错误是:

Traceback (most recent call last):
    File "/Users/m/loop.py", line 5, in <module>
    sys.stdout.write(countries[w]+" "+len(countries[w]))
TypeError: list indices must be integers or slices, not str

在这样的 for 循环中,循环变量从列表中获取 value,而不是它的索引。换句话说,w 不是每个国家的索引,而是国家本身。 此外,请注意,您不能像这样连接字符串和整数,因此您还必须将 len 的结果也转换为字符串:

from sys import stdout
countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"] # corrected spelling error Antartica -> Antarctica
for w in countries:
    stdout.write(f"{w} {len(w)}\n") # \n otherwise output will be in the same line (sys.stdout.write ISN'T print which adds \n by default at the end of line.

更短的版本

from sys import stdout
countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
[stdout.write(f"{w} {len(w)}\n") for w in countries] # [] are important and for Python 2 compatibility (and some IDEs and REPLs don't support f-strings) you can use **"%s %d" % (w, len(w))** instead of **f"{w} {len(w)}"**