好吧我會盡量簡單地解釋它。
你的input()
得到任何東西給它作爲string
。而且你需要對你需要的東西進行類型轉換。
在你的python解釋器中試試這個。
>>> a=input()
5
>>> a+10
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
a+10
TypeError: Can't convert 'int' object to str implicitly
爲什麼錯誤被拋出。這稱爲強類型語言。含義python不允許這樣做,你需要將它改爲你想要的類型來獲得你想要的。嘗試這個?
>>> a=input()
5
>>> int(a)+10
15
>>>
現在,它的作品,因爲我們增加了一個int()
這是類型轉換。現在在你的問題中,你只是將它們作爲字符串並使用它們。
這就是說你必須使用list(input())
將它們更改爲列表即使那些不需要的字符串來自你的字符串。
>>> a
'1 2 3 4'
>>> list(a)
['1', ' ', '2', ' ', '3', ' ', '4']
在這種情況下使用split()。默認情況下,your_string.split()
返回一個由空格分隔的列表。您甚至可以指定要分割的分隔符。因此在這裏沒有必要使用list()
>>> a
'1 2 3 4'
>>> a.split()
['1', '2', '3', '4']
print('Please type in your list number 1')
list_1=input().split()
print(list_1)
print('Great! Please type in your list number 2 ')
list_2=input().split()
print(list_2)
commonlist=[] # this will be the list containing common elements.
for i in range(len(list_1)):
if list_1[i] in list_2:
commonlist.append((list_1[i])) # this will put the common elements between the two lists in commonlist
print(commonlist)
輸出:
Please type in your list number 1
1 2 3 4
['1', '2', '3', '4']
Great! Please type in your list number 2
2 3 5 6
['2', '3', '5', '6']
['2', '3']
看看你得到了你想要的東西,雖然我建議這種方式來查找列表的共同要素。更簡單。
print('Please type in your list number 1')
list_1=input().split()
print('Great! Please type in your list number 2 ')
list_2=input().split()
commonlist = set(list_1)&set(list_2)
print(list(commonlist))
commonlist =集(LIST_1)&集(list_2)在一行結束。做它的蟒蛇方式。簡單的方法。
注意:這不會以有序方式提供常見項目。但你會得到所有常見的。
此外,原始代碼適用於python2.7,無需更改 – VMRuiz
@VMRuiz這是一個有效的點。但是我決定省略,因爲OP很清楚使用Python3。另外,在Python2中使用'input()'是邪惡的;-) –
當然,這只是對你的答案的沉迷,而不是抱怨 – VMRuiz