使用python交换二维数组

时间:2016-12-09 02:50:02

标签: python arrays

我需要帮助使用Python将2个元素交换为随机生成的以下类型的列表:

实际列表

list = [('a0', 'b5'), ('a0', 'b6'), ('a1', 'b0'), ('a1', 'b2'), ('a1', 'b3'), ('a1', 'b5'), ('a1', 'b6'), ('a2', 'b0'), ('a2', 'b2'), ('a2', 'b5'), ('a3', 'b4')]

使用'a1' 交换元素'a2'

Array [('a0', 'b5'), ('a0', 'b6'), ('a2', 'b0'), ('a2', 'b2'), ('a2', 'b5'), ('a3', 'b4'), ('a1', 'b0'), ('a1', 'b2'), ('a1', 'b3'), ('a1', 'b5'), ('a1', 'b6')]

这是我的代码:

r1 = random.randrange(1, 5, 1)
r2 = random.randrange(4, 9, 2)
a = ['a' + str(j) for j in range(r1)]
b = ['b' + str(j) for j in range(r2)] 

dd = []
total = math.floor((r1 * r2) * 80 / 100)
print("80% connection", total)

for x in a:
    for y in b:
        r3 = random.randrange(1, total, 2)
        if (r3 < 10):
            dd.append((x, y))
print("Connection", dd)

cop = [eb[0] for eb in dd]

s1 = random.randrange(len(a))
s2 = random.randrange(len(a))

print("Number to Swap", s1)
print("Range Number Two", s2)

for swp in range(len(dd)):
    if swp ==s1:
        for tes in range(len(a)):
            if a[s1] == cop[swp]:
                temp = dd[s1]
                dd[s1] = dd[s2]
                dd[s2] = temp
            else:
                for tes in range(len(a)):
                    if a[s2] == cop[swp]:
                        temp = dd[s1+1]
                        dd[s1+1] = dd[swp]
                        dd[swp] = temp

print("New Swap Array", dd)

1 个答案:

答案 0 :(得分:0)

这适用于与您的示例类似的列表,仅当实际列表包含以'a1''a2'作为第一个元素的元组时才交换元素,可以轻松修改以与其他和更多元素一起使用。

new_dd = []
first_els = []
second_els = []
end_els = []

for i in dd:
    if int(i[0][1]) < 1:
        new_dd.append(i)
    elif int(i[0][1]) > 2:
        end_els.append(i)
    elif int(i[0][1]) == 1:
        first_els.append(i)
    elif int(i[0][1]) == 2:
        second_els.append(i)

new_dd.extend(second_els)
new_dd.extend(first_els)
new_dd.extend(end_els)

print(dd)
print(new_dd)

输出:

[('a0', 'b1'), ('a0', 'b2'), ('a0', 'b3'), ('a1', 'b0'), ('a1', 'b1'), ('a1', 'b2'), ('a1', 'b3'), ('a2', 'b0'), ('a2', 'b1'), ('a2', 'b2'), ('a2', 'b3'), ('a3', 'b0'), ('a3', 'b2'), ('a3', 'b3')]
[('a0', 'b1'), ('a0', 'b2'), ('a0', 'b3'), ('a2', 'b0'), ('a2', 'b1'), ('a2', 'b2'), ('a2', 'b3'), ('a1', 'b0'), ('a1', 'b1'), ('a1', 'b2'), ('a1', 'b3'), ('a3', 'b0'), ('a3', 'b2'), ('a3', 'b3')]