用户输入两个城市名称并创建类似my_list = ["Dallas","SanJose"]
的列表,然后应返回以下函数:
"You would like to visit Dallas as city 1 and SanJose as city 2 on your trip"
这是我的代码:
def CreateSentence(my_list):
sentence = "You will like to visit "
for i, item in enumerate(my_list):
sentence = sentence + item, "as city",i+1,"and"
return sentence
我的回报目前为('You would like to visit Dallas' , 'as city', 1 , 'and')
我错过了第二个城市。
答案 0 :(得分:1)
您可以使用生成器表达式来收集城市和数字列表。然后使用format
创建字符串的内部重复部分。然后,您可以再次使用format
分别添加第一个和最后一个部分。
def CreateSentence(l):
middle = ' and '.join('{} as city {}'.format(city, num+1) for num,city in enumerate(l))
return 'You would like to visit {} on your trip'.format(middle)
>>> my_list = ["Dallas","SanJose"]
>>> CreateSentence(my_list)
'You would like to visit Dallas as city 1 and SanJose as city 2 on your trip'
答案 1 :(得分:0)
有一种内置方法,format()
。
>>> string = 'Hi my name is {}, and I am {}'
>>> print(string.format('Ian', 29))
'Hi my name is Ian, and I am 29`
答案 2 :(得分:0)
使用for循环,您需要将return语句放在循环外部,这样就不会过早退出循环。我还添加了一个if语句,只打印一次句子的开头,之后当循环不在“my_list”第一项时,添加多个城市。
>>def CreateSentence(my_list):
sentence = "You will like to visit "
for i, item in enumerate(my_list):
if i == 0:
sentence = sentence + item + " as city " + str(i+1)
else:
sentence += " and " + item + " as city " + str(i+1)
return sentence
>>my_list = ["Atlanta", "NewYork", "Portland"]
>>CreateSentence(my_list)
'You will like to visit Atlanta as city 1 and NewYork as city 2 and Portland as city 3'
答案 3 :(得分:0)
以通用方式编写函数总是一个好主意。这是使其适用于任意数量城市的一种方法。
def buildString(cities):
prefix = "You would like to visit "
suffix = " on your trip"
if len(cities) == 0:
return "No places to visit"
elif len(cities) == 1:
return prefix + cities[0] + suffix
else:
k = [ city + ' as city ' + str(count+1) for count, city in enumerate(cities)]
output = prefix + ", ".join(k[:-1]) + " and " + k[-1] + suffix
return output
<强>测试强>
>>> buildString(["Dallas"])
'You would like to visit Dallas on your trip'
>>> buildString(["Dallas","Houston"])
'You would like to visit Dallas as city 1 and Houston as city 2 on your trip'
>>> buildString(["Dallas","Houston","Sanjose"])
'You would like to visit Dallas as city 1, Houston as city 2 and Sanjose as city 3 on your trip'