Python:在数组的每个元素之后插入一个带有异常的字符串

时间:2015-03-08 12:42:20

标签: python

我有以下Python脚本。我想要做的是为random.shuffle(scenArray)添加几个字符串。具体来说,在数组的每个元素之后会有一个字符串,但是,数组中的第8个元素将需要一个不同的字符串。

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()

1 个答案:

答案 0 :(得分:0)

忽略所有代码,但是从您的描述和示例中删除:

  

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

您可以执行以下操作:

lst1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

lst2 = sum(([x,'A'] if i != 7 else [x,'B'] for (i,x) in enumerate(lst1)), [])

print lst2  # [1, 'A', 2, 'A', 3, 'A', 4, 'A', 5, 'A', 6, 'A', 7, 'A', 8, 'B', 9, 'A']

修改

分配给lst2的单行可以等效地重写为:

lst3 = []  # Initialize an empty list
for (i,x) in enumerate(lst1):
    if i != 7:
        lst3 += [x,'A']  # This is just concatenates the list [x,'A'] with lst3
    else:
        lst3 += [x,'B']

print lst3  # [1, 'A', 2, 'A', 3, 'A', 4, 'A', 5, 'A', 6, 'A', 7, 'A', 8, 'B', 9, 'A']

请注意,lst3 += [x, 'A']也可以写为

lst3.append(x)
lst3.append('A')

此外,sum()generator expression及其可选的开始参数一起使用。

最后,enumerate返回一个类似于生成器的对象,当迭代时,在每次迭代时生成一个(index, value)元组 - 请参阅我为一个小例子链接的文档。