[英]automate the boring stuff comma code
spam = ['apples', 'bananas', 'tofu', 'cats']
def stringmaker(data):
tempdata = 0
datastring = ''
stringlist = []
stringdata = ''
stringdata += ', '.join(data)
stringlist += stringdata.split()
tempdata = stringlist
tempdata = str(stringlist.insert(-1, 'and'))
datastring += ' '.join(stringlist)
print(datastring)
stringmaker(spam)
在 Automate the Boring Stuff with Python page 102 中,練習項目逗號代碼 - 逗號代碼
假設您有一個這樣的列表值: spam = ['apples', 'bananas', 'tofu', 'cats'] 編寫一個函數,將列表值作為參數並返回一個字符串,其中所有項目以逗號和一個空格,在最后一項之前插入 和 。 例如,將之前的垃圾郵件列表傳遞給該函數將返回 'apples、香蕉、豆腐和貓'。 但是你的函數應該能夠處理傳遞給它的任何列表值。
我編寫的代碼在本章的上下文中有效並保持不變。 我在這個網站和谷歌上查看了其他答案,我很驚訝我的代碼有多么不同,而且可能很愚蠢。 有人可以幫我指出我的代碼的所有不好的地方嗎?
我真的希望它盡可能像 Pythonic 和盡可能少的行。
它會完成你的工作:
spam = ['apples', 'bananas', 'tofu', 'cats',]
def commacode(spam):
return print(', '.join(spam[:-1]) + ' and ' + spam[-1])
commacode(spam)
def stringmaker(data):
return ", ".join(data[:-1]) + " and " + data[-1]
它的作用:加入列表但最后一個元素與“,”,然后添加“和”和最后一個元素
正如您問題中的評論所說,有時最好放棄“單行”以使您的代碼更具可讀性。
另請注意,如果數據是空列表,則此代碼目前不起作用
您可以使用以下內容:
words = ['apples', 'bananas', 'tofu', 'cats']
def spam(words):
if words: # prevents parsing an empty list
return ", ".join(words[:-1]) + ", and " + words[-1]
print spam(words)
# apples, bananas, tofu, and cats
注意:在英語中,您通常不會在and
之前使用commas
。
我做了這個練習,但考慮將用戶輸入作為一個列表:(lista == list 但在西班牙語中:3)
import sys
lista = []
while True:
print('enter the '+ str(len(lista) + 1) +' item in your list ' "(or enter nothing to stop)")
item = input()
if item == '':
break
lista = lista + [item]
lista[-1] = 'and ' + lista[-1]
print('your complete list is: \n' + (", ".join(lista)))
sys.exit()
這是我的解決方案,像你一樣,我花了三天時間來部分解決這個問題。 但這真的很棒。
這是代碼:
spam = ['apples', 'bananas', 'tofu', 'cats']
def list_string(the_list):
number_list = len(the_list)
if number_list == 1:
print(the_list[0])
elif number_list == 2:
print(the_list[0] + ' and ' + the_list[1])
elif number_list > 2:
for a in range(1):
print(', '.join(the_list[0 :len(the_list) - 1]) + ', and ' + the_list[len(the_list) - 1])
list_string(spam)
我有
list = []
for i in range(3):
value = str(input())
list.append(value)
list.insert(2, 'and')
print(list)
這樣,唯一需要根據您想要列表多長時間而改變的就是代碼的 range(3) 和 .insert(2, 'and') 部分。
我認為這提供了最好的輸出。(ps:我也是初學者)。
def ltos(list):
empty_string = ''
for i in list[:-2]:
empty_string += i + ", "
empty_string += list[-2]
empty_string += ' and ' + list[-1] + '.'
print(empty_string)
myex = ['dumb', 'retard', 'awkward', 'brainless', 'immature', 'ignored', 'invisible']
ltos(myex)
輸出:愚蠢、遲鈍、笨拙、無腦、不成熟、被忽視和隱形。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.