将列表的第 n 个元素与另一个第 n 个元素进行比较,然后交换 if 语句 true PYTHON 3.4.3

Comparing nth element of list with another nth element, then swapping if statement true PYTHON 3.4.3

我有两个列表。两者都与剧院的礼堂有关。
第一个列表包含这样的椅子占用情况:

xxooxoxoooxoxo
ooxoxooxoooxox
...
...

x = 占用,o = 空闲

我的第二个列表包含椅子的价格类别,如下所示:

33221111112233
33333222233333
...
...

我想制作第三个清单,显示空椅子的价格类别,如下所示:

3xxx11xx1xx2xx
...
...

所以基本上,我想用价格类别的数量交换 o-s。

这是我目前得到的:

我的 Rows 列表已经包含礼堂的入住率,我的 Category 列出了价格类别。

iRow = -1
icatRow = -1
chairNumber = -1
chairPrice = -1
Row = []
RowCat = []
for row in Rows:
    chairNumber = -1
    iRow += 1
    Row.append(row)
    if Row[iRow][chairNumber] == 'o':
        for cat in Category:
            icatRow += 1
            chairPrice += 1
            RowCat.append(cat)
            RowCat[icatRow][chairPrice] = Row[iRow][chairNumber]
        chairNumber += 1
    else:
        chairNumber += 1
print('{0}\n'.format(Row))

我在行 RowCat[icatRow][chairPrice] = Row[iRow][chairNumber] 中收到以下错误:

TypeError: 'str' object does not support item assignment

你能帮我解决这个问题吗?

谢谢!

你的代码不是很pythonic。试试像他这样的东西。

l1 = ['x','o','x']
l2 = [1,2,3]
l3 = [ r if r == 'x' else p for r,p in zip(l1,l2)]

returns 一个新列表

['x', 2, 'x']

我的输出是这样的:

def foo2():
    l1 = ['xxooxoxoooxoxo', 'ooxoxooxoooxox']
    l2 = ['33221111112233' , '33333222233333']
    l = []
    for i, row in enumerate(l1):
        t = [x if x is 'x' else l2[i][j] for j,x in enumerate(row) ]
        l.append(''.join(t))
    print l

你可以用 list comprehension and the ternary operator:

>>> list1 = ['x','x','o','o','x','o','x']
>>> list2 = [1,2,3,4,5,6,7]
>>> list3 = [list2[i] if j == 'o' else j for i, j in enumerate(list1)]
>>> list3
['x', 'x', 3, 4, 'x', 6, 'x']

试试这个:

for row, price in zip(rows, prices):
    new_row = ''
    for char,pri in zip(row,price):
        if char == 'o':
             new_row += str(pri)
        else:
              new_row += char

    print(new_row)

示例数据

rows = ['xoxo','oxox']
prices = ['1234','5678']

请注意,这里使用字符串等同于使用列表的列表,因为字符串在许多情况下可以被视为 Python 中的列表(例如遍历 string/iterating 中的所有字符列表的元素)

我出来了:

x2x4
5x7x

您当然希望更改行 print(new_row) 以执行您想对操作的行执行的任何操作