我是编程的新手,正在研究适用于Python 3的“自动化无聊的东西”一书。我见过其他一些人对“逗号代码”项目有疑问,但没有遇到我的具体问题。我想出了一个“工作”的起点,但是我不知道为什么我的打印功能给我的是int值而不是列表中的字符串。
def reList(items):
i = 0
newItems = str()
for items[i] in range(0,len(items)):
newItems = newItems + items[i] + ', '
print(newItems)
i=i + 1
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)
谢谢!
def reList(items):
#i = 0 # no need to initialize it.
newItems = str()
for i in range(0,len(items)): # i not items[i]
newItems = newItems + items[i] + ', '
print(newItems)
#i=i+1 # no need to do
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)
range(0,len(items))
返回数字0、1、2 ..最大len(items)
(不包括)
for items[i] in range(0,len(items))
正在制作items[i]
0、1、2 ...
这就是为什么它是印刷数字。
for i in range(0,len(items))
将i设为0、1、2 ...,items[i]
使您的项目位于i
列表的第th个位置。所以现在您得到的是字符串而不是数字。
更好的方法是-
def reList(items):
newItems = str()
for it in items:
newItems = newItems + it + ', '
print(newItems)
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句