我有一个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
在这样的for循环中,循环变量从列表中获取值,而不是其索引。换句话说,不是每个国家的指数,而是国家本身。 此外,请注意,不能像这样连接字符串和int,因此必须将
len
的结果也转换为字符串:较短版本
相关问题 更多 >
编程相关推荐