2016-02-12 97 views
2
#Say I have the lists 
l1 = [2,3,6,7,9] 
l2 = [11,14,16,20,21] 

# and a random number, say 8 
x = 8 

# And I want to change l1 so that if there is any number larger than 
# 8 it will be deleted, then 8 will be inserted into the end of l1 
# the output would look like this: [2,3,6,7,8] 

# And I want to change l2 so that if there is any number smaller than 
# 8 it will be deleted, then 8 will be inserted into the beginning of l2 
# the output would look like this: [8,11,14,16,20,21] 

我不知道如何去解決這個問題,並真誠感謝您的幫助。謝謝!將元素添加到列表中的特定位置

+0

我知道我應該使用if語句來刪除元素,並且我可以使用append函數將8放入列表中。但是,我不確定是否有更簡單的方法。 – PiccolMan

回答

4

使用列表理解:

l1 = [i for i in l1 if i <= 8] 
l1 = l1 + [8] 

(或l1.append(8)

和:

l2 = [i for i in l2 if i >= 8] 
l2 = [8] + l2 

(或l2.insert(0, 8)這大概是更快)

+0

謝謝!我的方法有許多代碼行。我知道我可以使用append將8放在列表的最後,但是我怎麼會在前面放一些東西? – PiccolMan

+1

@PiccolMan它在我的回答:) – Idos

+0

你實際上並不需要創建新的列表,可以使用'del'刪除列表項。 –

1

這裏有一個解決方案:

l1 = [i for i in l1 if i <= x] 

l1.append(x) 

l2 = [i for i in l2 if i >= x] 

l2.insert(0, x) 
+0

無論如何都已結束髮帖? ;) – Idos

+0

@Idos是的,但我使用的是變量而不是常量:) –

+1

你的'reverse()'「trick」是不必要的,而且是詳細的。 –

相關問題