У меня есть следующий скрипт Python. Я хочу добавить несколько строк в random.shuffle (scenArray). В частности, после каждого элемента массива будет строка, однако для восьмого элемента в массиве потребуется другая строка.Python: вставить строку после каждого элемента массива с исключением
E.g. если массив 1,2,3,4,5,6,7,8,9
Я хочу это 1,A,2,A,3,A,4,A,5,A,6,A,7,A,8,B,9,A
Любая помощь очень ценится.
import random
# General comment: some of the script might be confusing because python
# uses zero-based numbering to index arrays
# read in the full list of scenario x conditions
f = open('scenarioList.xml', 'U')
data = f.read()
f.close()
inst = data.split("\n\n")
# This specifies which scenarios are in which counterbalancing group
cGroups = [[0,1,2,3,4],
[5,6,7,8,9],
[10,11,12,13,14]]
conds = [inst[0:15],inst[15:30],inst[30:45]] # the xml strings divided up by condition
# this is the counterbalancing scheme (latin square)
cScheme = [[1,2,3],
[1,3,2],
[2 ,1 , 3],
[2 , 3 , 1],
[3 , 1 , 2],
[3, 2 , 1]]
# change the second index in the range to loop up to 60; set to 12 now for testing
for subj in range(1,12):
cRow = cScheme[(subj-1)%6] # use the modulus operator to find out which row to use in counterbalancing table
scenArray = []
# loop across scenario groups and look up their assigned interruption condition for this subj
for group in range(0,3):
#conds[cScheme[group]][i]
scenArray.extend([ conds[cRow[group]-1][i] for i in cGroups[group]]) # use extend and not append here
# randomize order of arrays---this is something you might modify to control this a bit more
random.shuffle(scenArray)
f = open('scenarios' + str(subj) + 'xml', 'w')
f.write('\r\n\r\n'.join(scenArray))
f.close()
Для того, чтобы быть четкими, вы хотите, чтобы эти элементы были добавлены * после * перетасовки, не так ли? Потому что, если вы хотите, чтобы они были добавлены до того, как список был перетасован, вы можете просто добавить их в конец списка. – jedwards
Что вы хотите перетасовать в '1, A, 2, A, 3, A, 4, A, 5, A, 6, A, 7, A, 8, B, 9, A'? – Kasramvd
Да, я хочу, чтобы они были добавлены после перетасовки :) –