2016-07-04 75 views
1
list = [] 

def lecture(x): 
    for x in range(1,x): 
     print 'lecture', x 

所以我有这样的代码,给出的循环和追加到列表

lecture 1 
lecture 2 

lecture(3)输入的结果。现在,当我更改代码以

list = [] 

def lecture(x): 
    for x in range(1,x): 
     y = 'lecture', x 
      print y 

我得到的

('lecture', 1) 
('lecture', 2) 

输出最后,我想知道这是为什么,因为我试图找到追加第一的办法的情况下结果,在:

lecture 1 
lecture 2 

成一个列表,但我不能,因为我得到一个列表用逗号等从它的数量分离讲座号码

+2

因为回答'y '是一个元组,这就是当你打印它们时元组的样子。尝试使用'str.format'显式的字符串格式,或者使用print函数来更好地控制'from __future__ import print_function'(或者移到Python 3.x,你应该这样做)。 – jonrsharpe

+0

为什么我的大学部门建议我们不要以3.x开头? – FreeLand

+1

'list'变量与此有什么关系?你没有在代码中使用它。 – Barmar

回答

3

你得到那个奇怪的符号,因为'lecture', x是一个tuple。充当列表的数据类型,但是不灵活的列表。你不能轻易改变它们。您必须使用+运算符而不是逗号将这两个值放入一个变量中。

将值放入列表中是通过append函数完成的。

list = [] 

def lecture(x): 
    for x in range(1,x): 
     y = 'lecture' + str(x) 
     list.append(y); 
lecture(5) 

还要注意: y = 'lecture' + str(x)str(x)是确保不同的数据类型(int和string)不冲突。因为String + Int是不可能的。

  • 5(INT)+ 5(INT)是10
  • 5(字符串)+ 5(字符串)是55.
  • 但5(字符串)+ 5(INT)是错误的。
0

交换y = 'lecture', x有:

y = 'lecture ' + str(x) 

这将变量x追加到'lecture'并将其设置可变y

+0

'str(x)'而不是'x' – Zimm1

0

使用表达式y = 'lecture', x,您正在创建一个元组。创建一个空的列表,而是和与附加价值给它的循环:

def lecture(x): 
    lecture_list=[] 
    for item in range(1,x+1): 
     y='lecture '+str(item) 
     lecture_list.append(y) 
    return lecture_list 
0

的另一种方法:

class Lectures(object): 
    def __init__(self, x): 
     self.x = x 
    def __iter__(self): 
     for i in range(1, self.x): 
      yield "lecture" + i 

这里可迭代类讲座制成。

首先,你需要对它进行初始化,通过X作为一个属性:

lectures = Lectures(x) 

然后你可以使用它作为一个迭代:

list_of_lectures = list(lectures) 

for lecture in lectures: 
    do_something