如何交换所有属性的值?我想要FieldIP = 1.MomentIP = 1 FieldOP = 3,依此类推。
FieldIP =3 FieldOP =1
MomentIP =3 MomentOP =1
NormalizeMomentIP =3 NormalizeMomentOP =1
ixfwdIP =3 ixfwdOP =1
iyfwdIP =3 iyfwdOP =1
ixbwdIP =3 ixbwdOP =1
iybwdIP =3 iybwdOP =1
MsAvgIP =3 MsAvgOP =1
MsStdIP =3 MsStdOP =1
HkIP =3 HkOP =1
NegFieldIP =3 NegFieldOP =1
NegNormalizeMomentIP =3 NegNormalizeMomentOP =1
NegFieldBotIP =3 NegFieldBotOPx` =1
NegNormalizeMomentBotIP =3 NegNormalizeMomentBotOP =1
如何交换所有属性的值?有没有更短的方式? 这是我所做的代码。如果我确实完成了所有14个属性,它将会很长,因为我必须声明28变量......
x = FieldIP
y = FieldOP
...
if ( HkOP > HkIP):
FieldOP = x
FieldIP = y
print "Swapped"
FieldIP =1 FieldOP =3
MomentIP =1 MomentOP =3
NormalizeMomentIP =1 NormalizeMomentOP =3
ixfwdIP =1 ixfwdOP =3
iyfwdIP =1 iyfwdOP =3
ixbwdIP =1 ixbwdOP =3
iybwdIP =1 iybwdOP =3
MsAvgIP =1 MsAvgOP =3
MsStdIP =1 MsStdOP =3
HkIP =1 HkOP =3
NegFieldIP =1 NegFieldOP =3
NegNormalizeMomentIP =1 NegNormalizeMomentOP =3
NegFieldBotIP =1 NegFieldBotOPx` =3
NegNormalizeMomentBotIP =1 NegNormalizeMomentBotOP =3
答案 0 :(得分:2)
以短的方式交换两个变量
a, b = b, a
答案 1 :(得分:1)
我假设你的这些数据是某种文本文件。
尝试这样的事情:
import re
# read your data
lines = open('mytable.txt').readlines()
# regex to capture your 'values'
regex = re.compile(r'(.*?=)([0-9]+)(.*?=)([0-9]+)')
for line in lines:
# for each line, match the value groups and substitute swapped values
print regex.sub(r'\1\4\3\2', line)
应该使用交换值打印表,并保留空白。
答案 2 :(得分:0)
您可以迭代本地变量来执行此操作:
key = key2 = None
for key in locals():
if key.endswith('OP'):
key2 = key[:-2] + 'IP'
if locals()[key] > locals()[key2]:
locals()[key], locals()[key2] = locals()[key2], locals()[key]
print 'swapped'
您必须在for循环之前声明key
和key2
,而不是在其中。