簡體   English   中英

python3中的列表和循環

[英]List & Loops in python3

這是對象:編寫一個函數以獲取2個列表L1和L2,並構建並返回僅由列表L1和列表L2中的元素構成的第三個列表L3,即排除僅在L1或僅在L2中的任何值。

問題:我陷入了循環(只會采用alist和blist共享的值)。

我的代碼:

alist=input("Enter words separated by space: " ).split(" ")
blist=input("Enter words separated by space: " ).split(" ")
clist=[" "]
for i in alist,blist:
    if alist(i)==blist(i):
        clist=alist(i)+blist(i)
        return clist
clist = []
for i in alist:
    if i in blist:
        clist.append(i)

print clist
  1. 您可以使用in運算符來檢查另一個列表中是否存在一個值。

    例如:

     alist = ["a", "b", "c"] print "b" in alist # will print True print "d" in alist # will print False 
  2. 您可以在列表中使用append方法添加新項目。

純列表理解

>>> alist = ["a", "b", "c"]
>>> blist = ["a", "d", "c"]
>>> [var for var in alist if var in blist]
['a', 'c']

以上是列表理解。 文件資料

暫無
暫無

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

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