如何在任意位置将元素插入列表?

时间:2017-06-04 21:15:09

标签: python list python-3.x

我有这个

>>> a = [1, 4, 7, 11, 17]
>>> print a
[1, 4, 7, 11, 17] 

有没有办法添加4个字符' - '例如,在其他元素之间随机地实现

['-', 1, '-', 4, 7, '-', '-', 11, 17]

4 个答案:

答案 0 :(得分:6)

你可以这样做:

isset($_POST['stayLoggedIn'])

循环体在import random for _ in range(4): a.insert(random.randint(0, len(a)), '-') '-'(包括)之间的随机索引处插入0。但是,由于插入列表是len(a),因此根据插入的数量和列表的长度,在性能方面构建新列表可能会更好:

O(N)

答案 1 :(得分:2)

您可以使用迭代器和'-'随机交错random.sample()

In [1]:
a = [1, 4, 7, 11, 17]
pop = [iter(a)]*len(a) + [iter('-'*4)]*4
[next(p) for p in random.sample(pop, k=len(pop))]

Out[1]:
['-', '-', 1, '-', 4, 7, 11, '-', 17]

答案 2 :(得分:1)

Python有插入(索引,值)列表方法,可以解决这个问题。 你想要的是:

import random

l = [1, 2, 3, 4]
for x in range(0, 4): # this line will ensure 4 element insertion
   l.insert(random.randrange(0, len(l)-1), '-')

randrange()将从列表的索引范围内生成随机整数。 多数民众赞成。

答案 3 :(得分:0)

由于性能不是问题,以下是您的问题的另一种解决方案(根据@AChampion评论修改):

from __future__ import print_function

import random

_max = 4
in_list = [1, 4, 7, 11, 17]
out_list = list()

for d in in_list:
    if _max:
        if random.choice([True, False]):
            out_list.append(d)
        else:
            out_list.extend(["-", d])
            _max -= 1
    else:
        out_list.append(d)

# If not all 4 (-max) "-" have not been added, add the missing "-"s at random.
for m in range(_max):
    place = random.randrange(len(out_list)+1)
    out_list.insert(place, "-")

print(out_list)

给出了:

$ for i in {1..15}; do python /tmp/tmp.py; done
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, '-', 11, 17, '-']
[1, '-', 4, '-', '-', 7, '-', 11, 17]
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
[1, 4, '-', 7, '-', '-', '-', 11, 17]
['-', 1, 4, 7, '-', 11, '-', '-', 17]
[1, 4, '-', '-', '-', 7, '-', 11, 17]
['-', '-', 1, 4, 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
['-', 1, '-', 4, '-', 7, 11, '-', 17]
[1, '-', 4, '-', 7, '-', 11, '-', 17]
[1, '-', '-', 4, '-', 7, 11, '-', 17]
相关问题