Adding an element to a specific location in a list

时间:2016-02-12 20:13:26

标签: python list append

#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]

I'm not sure how to go about this, and would sincerely appreciate some help. Thanks!

2 个答案:

答案 0 :(得分:4)

Use list comprehension:

manager

(or l1 = [i for i in l1 if i <= 8] l1 = l1 + [8] )

and:

l1.append(8)

(or l2 = [i for i in l2 if i >= 8] l2 = [8] + l2 which is presumably faster)

答案 1 :(得分:1)

Here's a solution:

Opaque