gpt4 book ai didi

python - 使用 Python : Comma Code 自动化无聊的事情

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:20 25 4
gpt4 key购买 nike

我目前正在学习这本初学者书籍,并完成了其中一个练习项目“逗号代码”,该项目要求用户构建一个程序:

takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the below spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

spam = ['apples', 'bananas', 'tofu', 'cats']

我对问题的解决方案(效果很好):

spam= ['apples', 'bananas', 'tofu', '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', 'bananas', 'tofu', 'cats']
listTostring(spam)

输出:苹果、香蕉、 bean 腐和猫

最佳答案

使用 str.join() 连接带有分隔符的字符串序列。如果对除最后一个 之外的所有单词都这样做,则可以在此处插入' 和':

def list_thing(words):
if len(words) == 1:
return words[0]
return '{}, and {}'.format(', '.join(words[:-1]), words[-1])

分解:

  • words[-1] 获取列表的最后一个元素。 words[:-1] 切片 生成一个新列表,其中包含除最后一个单词外的所有单词

  • ', '.join() 产生一个新的字符串,str.join() 的参数的所有字符串都与 连接在一起' , '。如果输入列表中只有 一个 元素,则返回该元素,未连接。

  • '{}, and {}'.format() 将逗号连接的词和最后一个词插入到模板中(用牛津逗号完成)。

如果你传入一个空列表,上面的函数会抛出一个IndexError异常;如果您觉得空列表是该函数的有效用例,您可以在函数中专门测试该情况。

所以上面将 除了最后一个单词', ' 连接起来,然后将最后一个单词与 ' 和 ' 添加到结果中.

请注意,如果只有一个词,您就得到那个词;在那种情况下没有什么可加入的。如果有两个,您将得到 'word1 和 word 2'。更多单词会生成 'word1, word2, ... and lastword'

演示:

>>> def list_thing(words):
... if len(words) == 1:
... return words[0]
... return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
...
>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> list_thing(spam[:1])
'apples'
>>> list_thing(spam[:2])
'apples, and bananas'
>>> list_thing(spam[:3])
'apples, bananas, and tofu'
>>> list_thing(spam)
'apples, bananas, tofu, and cats'

关于python - 使用 Python : Comma Code 自动化无聊的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38824634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com