随机选择两个列表的某些索引以创建两个新列表

时间:2018-09-23 22:19:05

标签: python python-3.x list indices

说我有两个列表:

A = ['cat', 'dog', 'cow', 'pig', 'monkey']
B = ['Felix', 'Fido', 'Moo', 'Trump', 'King Kong']

现在,我想通过选择3个随机索引(不替换)来创建lists Alist B,同时保持AB的值之间的关系。 / p>

例如,

随机选择的索引:4, 0, 3

因此

A = ['monkey', 'cat', 'pig']
B = ['King Kong', 'Felix', 'Trump']

有没有一种方法,而无需编写for循环,该循环重复3次以选择随机索引?

5 个答案:

答案 0 :(得分:2)

您可以zip列表,然后用random.sample随机选择3对,最后再次将对分成单独的列表:

import random

pairs = list(zip(A, B))  # make pairs out of the two lists
pairs = random.sample(pairs, 3)  # pick 3 random pairs
A1, B1 = zip(*pairs)  # separate the pairs

这是逐步发生的事情:

>>> list(zip(A, B))
[('cat', 'Felix'), ('dog', 'Fido'), ('cow', 'Moo'), ('pig', 'Trump'), ('monkey', 'King Kong')]
>>> random.sample(_, 3)
[('monkey', 'King Kong'), ('pig', 'Trump'), ('dog', 'Fido')]
>>> list(zip(*_))
[('monkey', 'pig', 'dog'), ('King Kong', 'Trump', 'Fido')]

答案 1 :(得分:1)

Python有一个示例函数,该函数无需替换即可进行选择。您可以从索引中采样,并将采样应用于输入。

from random import sample

A = ['cat', 'dog', 'cow', 'pig', 'monkey']
B = ['Felix', 'Fido', 'Moo', 'Trump', 'King Kong']
k = 3

samp = sample(range(len(A)), k)
A_p = [A[i] for i in samp]
B_p = [B[i] for i in samp]

答案 2 :(得分:1)

您可以使用:

data['timeobject'] = datetime.time(data['start_time'], axis = 1)

答案 3 :(得分:1)

我认为我最喜欢zip答案,但我会使用列表理解

import random   

l1 = ['cat', 'dog', 'cow', 'pig', 'monkey']
l2 = ['Felix', 'Fido', 'Moo', 'Trump', 'King Kong']
r = [random.randint(0, len(l1)-1) for i in range(3)]

A = [l1[i] for i in r]
B = [l2[i] for i in r]
~/python/stackoverflow/9.23$ python3.7 loop.py 
['monkey', 'cow', 'cat']
['King Kong', 'Moo', 'Felix']

答案 4 :(得分:0)

尽管可以将其委派给一个函数或将其打扮为列表理解,但您无法避免循环。 不过,您可以遍历每个列表一次。

#lets assume your randomly selected numbers are 4, 0 and 3
indices = (4,0,3)
# lets assign an ordinal to each index
indices_ordinals = [(ind, ord) for ind, ord in enumerate(indices)]
# now we can re sort the indices, since we have recorded their original sequence
indices_ordinals.sort(key = lambda x: x[0])
# now go through the lists (for simplicity we assume they have equal number of elemwnts) and fill the output dicts
csi = 0 # csi is the index that we are looking for currently
A1 = {}
B1 = {}
for i, elem in enumerate(A):
    if i == indices_ordinals[csi][0]:
        A1[indices_ordinals[1]] : elem
        csi += 1
csi =0
for i, elem in enumerate(B):
    if i == indices_ordinals[csi][0]:
        B1[indices_ordinals[1]] : elem
        csi += 1
#now we only need to sort A1 and B1 to get desired output
A2=[A1[i] for i in sorted(A1)]
B2=[B1[i] for i in sorted(B1)]