在循环中附加到数组

时间:2015-07-25 20:17:01

标签: python arrays append

我想在x = 0到group1时附加losowanie1 [0],依此类推(当x = 1到group2时,losowanie1 [0] ...)。与losowanie2 [0]相同,但它来自其他List。

import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']
List2 = ['FFFF','GGGG','HHHH','IIIII','JJJJJ']

Gruop1 = []
Group2 = []

for x in range (len(List1)):
    losowanie1 = random.sample(List1,1)
    losowanie2 = random.sample(List2,1)
    # Here i would like to append losowanie1[0] when x = 0 to group1 and so on ( losowanie1[0] when x = 1 to group2...)
    List1.remove(losowanie1[0])

我试过了:

('Group' + str(x+1)).append(losowanie1[0])

但显然我不能追加到字符串中。 我可以不循环地做,但想让我的代码更专业。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用dictionarykeys)制作'Group' + str(x+1)' 然后为list添加一个值!

import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']

base_name = "Group"
my_dic = dict()
for x in range(len(List1)):
    my_dic[base_name + str(x +1)] = []

for x in range (len(List1)):
    losowanie1 = random.sample(List1,1)
    my_dic[base_name + str(x +1)].append(losowanie1[0])
    List1.remove(losowanie1[0])
print(my_dic)

结果

{'Group3': ['DDDD'], 'Group4': ['BBBBB'], 'Group1': ['EEEE'], 'Group2': ['CCCCC'], 'Group5': ['AAAA']}