从列表中创建句子

1 投票
4 回答
574 浏览
提问于 2025-05-01 09:23

用户输入两个城市的名字,然后创建一个列表,比如 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'),但是我缺少了第二个城市。

暂无标签

4 个回答

0

这个问题有一个内置的方法可以解决,叫做 format()

>>> string = 'Hi my name is {}, and I am {}'
>>> print(string.format('Ian', 29))
'Hi my name is Ian, and I am 29`
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'
0

在使用for循环的时候,你需要把返回的语句放在循环外面,这样才能避免提前退出循环。我还加了一个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'
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'

撰写回答