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

2024-09-30 20:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

使用打印的原始代码:

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

Tags: inimportlen错误stdoutsyscountrieswrite
1条回答
网友
1楼 · 发布于 2024-09-30 20:31:57

在这样的for循环中,循环变量从列表中获取值,而不是其索引。换句话说,不是每个国家的指数,而是国家本身。 此外,请注意,不能像这样连接字符串和int,因此必须将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)}"**

相关问题 更多 >