2016-11-20 82 views
3

我正在通过“Automate the Boring Stuff with Python”书工作,并且陷入了其中一个练习问题。我的解决方案在shell中工作,但不是当我尝试将它作为程序运行时。这里的问题是提示:无法在shell中获取代码以作为程序工作

假设你有一个列表值是这样的:

spam = ['apples', 'bananas', 'tofu', 'cats'] 

编写一个函数,接受一个列表值作为参数,并返回一个字符串的所有被分离的项目逗号和空格,并插入最后一项之前。例如,将以前的垃圾邮件列表传递给函数将返回'苹果,香蕉,豆腐和猫'。但是你的函数应该能够处理传递给它的任何列表值。

这里是我的代码:

def listToString(usersList): 
    myStr = ', '.join(str(i) for i in usersList[0:-1]) # converts all but last list element to string and joins with commas 
    myStr = myStr + ' and ' + str(usersList[-1]) # adds on "and", converts final list element to string and adds to myStr 
    print(myStr) 

myList = input() 
listToString(myList) 

当我在shell定义列表,并在其上运行上述步骤,我得到的结果,我想:

'apples, bananas, tofu and cats' 

但是,当我尝试在上面的程序中将步骤组合在一起,结果是这样的:

[, a, p, p, l, e, s, ,, , b, a, n, a, n, a, s, ,, , t, o, f, u, ,, , c, a, t, s and ] 

任何想法?

非常感谢您花时间阅读本文。关于这个同样的练习题还有一些其他的话题(herehere),但我仍然坚持,所以我继续前进并发布。

+0

您需要将'listToString'传递给实际列表,而不是字符串。 'input'(在Python 3中)_always_返回一个字符串。 –

+1

练习并没有说你应该从用户输入中获得一个列表。只需将'spam'列表编码到您的脚本中即可。 –

+0

对于所有告诉OP将'input'返回的字符串转换为列表的人:请阅读这个问题!练习是编写一个接受_list_的函数。您添加了不必要的额外复杂功能,这对于此练习来说不是必需的。 –

回答

2

input()返回一个字符串。你需要转换的字符串中使用str.split

myList = input().split() # 'apple banana' -> ['apple', 'banana'] 

否则,字符串被反复传递给函数之前列出;产生每个人物作为物品。

>>> a_string = 'abcd' 
>>> for x in a_string: 
...  print(x) 
... 
a 
b 
c 
d 
1

由于您收到的input是字符串,而不是list,所以出现问题。
首先将输入转换为列表,然后运行你的函数。

尝试在输入上使用.split()

1

当绳子的输入,确保输入的是 “分裂()”,将其转换成字符串:

def listToString(usersList): 
     myStr = ', '.join(str(i) for i in usersList[0:-1]) # converts all but last list element to string and joins with commas 
     myStr = myStr + ' and ' + str(usersList[-1]) # adds on "and", converts final list element to string and adds to myStr 
     print(myStr) 

myList = input().split(',') 
listToString(myList) 

输入:

apples,bananas,tofu,cats 

输出:

apples, bananas, tofu and cats 
1

你只需要按照p roblem陈述的细节,

def listToString(userList): 
    return ', '.join(userList[:-1]) + ' and ' + userList[-1] 

执行:

In [13]: listToString(spam) 
Out[13]: 'apples, bananas, tofu and cats' 

现在,当您从用户接受列表中,您接受原始字符串, 你需要将其转换成列表。

In [16]: mylist = input() 
'apples,bananas,tofu,cats' 

In [19]: mylist.split(',') 
Out[19]: ['apples', 'bananas', 'tofu', 'cats'] 

In [20]: userList = mylist.split(',') 

In [21]: listToString(userList) 
Out[21]: 'apples, bananas, tofu and cats'