使用for循环在Python列表中存储用户值

时间:2016-10-12 04:48:57

标签: python

这是我的代码,要求用户输入城市数量,并且只允许输入该数量的城市 要求是使用For Loop

global number_of_cities
global city
global li
global container
li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
    city = (raw_input("Enter City Name -->"))
    li = city
    print li[]

2 个答案:

答案 0 :(得分:1)

假设您想要li中的城市列表,您可以执行以下操作:

li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
    li.append(raw_input("Enter City Name -->"))
print(li)

不需要变量前面的global,也不需要在开头定义其他变量,只需要空列表。

实际上这是学习列表理解的一个很好的例子,例如

n = int(raw_input("Enter Number of Cities: "))
li = [raw_input('City Name: ') for city in range(n)]
print(li)

这给出了:

>>> n = int(raw_input("Enter Number of Cities: "))
Enter Number of Cities: 4
>>> li = [raw_input('City Name: ') for city in range(n)]
City Name: London
City Name: Paris
City Name: Dubai
City Name: Sidney
>>> print(li)
['London', 'Paris', 'Dubai', 'Sidney']

答案 1 :(得分:0)

而不是

li.append(city)

使用

function moveForm() {
  var myDId = DriveApp.getRootFolder().getId();

  var rootFolder = DriveApp.getFolderById(myDId);
  var archiveFolder = DriveApp.getFolderById("0B2GEcLNd0NO4ZEMtbGZBdmZibzA");

  var newForms = rootFolder.getFilesByName('Let\'s meet!');
  while (newForms.hasNext()) {
    var newForm = newForms.next();
    archiveFolder.addFile(newForm)
    rootFolder.removeFile(newForm);
  }
}

希望有所帮助。