簡體   English   中英

如何獲取前兩個列表中的公共元素並保存到 python 3 中的新列表?

[英]How can i get the common elements in the first two list and save to a new list in python 3?

list1 = [input("Enter the values for the first list: ")]
list2 = [input("Enter the values for the second list: ")]
print(list1)
print(list2)
list3 = []
for element in list1:
    if element in list2:
        list3 = list2.append(element)
print(list3)

這是我嘗試過的。 但我得到一個空列表作為list3!

list1 = [input("Enter the values for the first list: ")]
list2 = [input("Enter the values for the second list: ")]

list1 和 list2 將是一個字符串列表。 因此你得到 list3 為空。 PFB 代碼和 o/p:

list1 = [input("Enter the values for the first list: ")]
list2 = [input("Enter the values for the second list: ")]
print(list1)
print(list2)
list3 = []
for element in list1:
    print(type(element))
    if element in list2:
        list3.append(element)

print(list3)

output:

Enter the values for the first list: 1 2 3 4 5
Enter the values for the second list: 2 3 4 5 6 
['1 2 3 4 5']
['2 3 4 5 6']
<class 'str'>
[]

添加正確的方法。 請參見下文,例如。 獲取 list1 和 list2:

# list1 = [input("Enter the values for the first list: ")]
# list2 = [input("Enter the values for the second list: ")]
list1 = [int(item) for item in input("Enter the 1st list items : ").split()]
list2 = [int(item) for item in input("Enter the 2nd list items : ").split()]

print('1st list: ',list1)
print('2nd list: ',list2)
list3 = []
for element in list1:
    if element in list2:
        list3.append(element)

print('common: ', list3)

output:

Enter the 1st list items : 1 2 3 4 5
Enter the 2nd list items : 3 4 5 6 7
1st list:  [1, 2, 3, 4, 5]
2nd list:  [3, 4, 5, 6, 7]
common:  [3, 4, 5]

您不能使用[input('Enter numbers: ')]來獲取列表的數字。 這將創建一個包含輸入字符串的列表。 您真正需要做的是首先輸入變量中的數字,比如說list1_inp ,然后使用nums = list1_inp.split(' ')根據空格拆分list1_inp 現在您可以遍歷您的列表來檢查常見元素。

list1_inp = input('Enter the elements separated by spaces : ')
nums = list1_inp.split()
list2_inp = input('Enter the elements separated by spaces : ')
nums2 = list2_inp.split()

temp = nums2
final = []
for elem in nums:
   if elem in temp:
      final.append(elem)
      temp.remove(elem)

print(final)
mylist1 = [1,2,3,4,5]
mylist2 = [2,3,4,5,6] # let these be the two lists


def func():
    mylist3 = []  # This is the list where the common numbers append
    for x in mylist1:
        for y in mylist2:
            if x==y:
                mylist3.append(x)
            else:
                pass
return mylist3
            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM