目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,使用Python写的一些自动化小工具(附代码)构建一个程序:
spam = ['apples','bananas','
我对问题的解决方案(效果非常好):
spam= ['apples','cats']
def list_thing(list):
new_string = ''
for i in list:
new_string = new_string + str(i)
if list.index(i) == (len(list)-2):
new_string = new_string + ',and '
elif list.index(i) == (len(list)-1):
new_string = new_string
else:
new_string = new_string + ','
return new_string
print (list_thing(spam))
我唯一的问题是,有什么方法可以缩短我的代码吗?或者让它更“pythonic”?
这是我的代码.
def listTostring(someList):
a = ''
for i in range(len(someList)-1):
a += str(someList[i])
a += str('and ' + someList[len(someList)-1])
print (a)
spam = ['apples','cats']
listTostring(spam)
解决方法
使用str.join()连接带有分隔符的字符串序列.如果你对除了最后一个之外的所有单词都这样做,你可以在那里插入’和’:
def list_thing(words):
if len(words) == 1:
return words[0]
return '{},and {}'.format(','.join(words[:-1]),words[-1])
打破这个:
> words [-1]获取列表的最后一个元素.单词[: – 1]将列表切片以生成包含除最后一个单词之外的所有单词的新列表.
>’,’.join()生成一个新字符串,str.join()的所有参数字符串都与’,’连接.如果输入列表中只有一个元素,则返回该元素,取消连接.
>'{}和{}’.format()将逗号连接的单词和最后一个单词插入模板(以牛津逗号填写).
如果传入一个空列表,上面的函数将引发一个IndexError异常;如果您觉得空列表是函数的有效用例,您可以在函数中专门测试该情况.
所以上面用’,’连接除了最后一个单词之外的所有单词,然后用’和’将最后一个单词添加到结果中.
请注意,如果只有一个单词,则会得到一个单词;在这种情况下没有什么可以加入的.如果有两个,你得到’word1和word 2′.更多的单词产生’word1,word2,…和lastword’.
>>> def list_thing(words):
... if len(words) == 1:
... return words[0]
... return '{},words[-1])
...
>>> spam = ['apples','cats']
>>> list_thing(spam[:1])
'apples'
>>> list_thing(spam[:2])
'apples,and bananas'
>>> list_thing(spam[:3])
'apples,and tofu'
>>> list_thing(spam)
'apples,and cats'