python支持str_Python:<str和in之间不支持

啊,但是for i in array遍历每个元素,所以if i < len(item)-1:比较一个字符串(数组元素item)和一个整数(len(item)-1:)。

所以,问题是您误解了Python中的how ^{} works。

快速修复?

您可以将for替换为for i in range(len(array)),因为range的工作方式如下:>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

从而获得:spam = ['apples', 'bananas', 'tofu', 'cats']

def printSpam(item):

for i in range(len(item)):

if i < len(item)-1:

print (','.join(str(item[i])))

else:

print ("and ".join(str(item[len(item)-1])))

return

printSpam(spam)

不过,输出可能不会是您所期望的那样,因为'c'.join(array)在数组的各个元素之间使用'c'作为“粘合剂”,如果不是字符数组,那么什么是字符串?>>> ','.join("bananas")

'b,a,n,a,n,a,s'

因此,输出将是:a,p,p,l,e,s

b,a,n,a,n,a,s

t,o,f,u

cand aand tand s

我们无论如何都可以做得更好。

Python支持所谓的slice notation和负索引(从数组末尾开始)。

自从>>> spam[0:-1]

['apples', 'bananas', 'tofu']

>>> spam[-1]

'cats'

我们有那个>>> ", ".join(spam[0:-1])

'apples, bananas, tofu'

以及>>> ", ".join(spam[0:-1]) + " and " + spam[-1]

'apples, bananas, tofu and cats'

因此,您可以简单地编写函数def printSpam(item):

print ", ".join(item[0:-1]) + " and " + item[-1]

就这样。

它起作用了。

附:关于Python和数组表示法的一件事是:>>> "Python"[::-1]

'nohtyP'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值