使用Python自动化无聊的东西:逗号代码
目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,要求用户构建一个程序:
spam = ['apples','bananas','tofu','cats'] 我对问题的解决方案(效果非常好): 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]将列表切片以生成包含除最后一个单词之外的所有单词的新列表. 如果传入一个空列表,上面的函数将引发一个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' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |