我有一个表格,它长这样:
PotA PotB PotC PotD PotE
A + + + + +
B - ? + + ?
C + + + + +
D + - + - +
E + + + + +
从这里开始,我需要找到所有可能的“+”、“-”和“?”组合,针对(PotA和PotB)、(PotA和PotC)等所有组合,一直到(PotA、PotB、PotC、PotD和PotE)。实际上,“Pot”行还可以继续下去,但为了简化起见,我只展示到PotE。
为了做到这一点,首先,我按照以下方式读取文件,然后生成两个组合的所有可能性,以计算每个可能性的数量。
def readDatafile():
filename = ("data.txt")
infile = open(filename,'r')
for line in infile.readlines():
line = line.strip()
print (line) # just to check the data, need to carry on from here.
"""Generate all possible permutations for later count"""
def doPermutations(items, n):
if n == 0:
yield ''
else:
for i in range(len(items)):
for base in doPermutations(items, n - 1):
yield str(items[i]) + str(base)
def makeAllPossibleList():
nlength = 2 # This should go outside of the function and will be same as the number of Pots
lpossibility = ['+', '-', '?']
litems = []
for i in doPermutations(lpossibility, int(nlength)):
litems.append(i)
for x in items:
print (x) # This generate all the possible items for combination of two
所以,最终结果将会是这样的:
Combination: Possibility Count
PotA, PotB: ++ 3
PotA, PotB: +- 1
PotA, PotB: +? 0
PotA, PotB: -+ 0
PotA, PotB: -- 0
PotA, PotB: -? 1
PotA, PotB: ?+ 0
PotA, PotB: ?- 0
PotA, PotB: ?? 0
PotA, PotC: ...
PotA, PotC: ...
.......
PotA, PotB, PotC, PotD, PotE: +++++ 3
PotA, PotB, PotC, PotD, PotE: ++++- 0
PotA, PotB, PotC, PotD, PotE: ++++? 0
.......
有没有好的Python方法来解决这个问题?我是否需要将带有标题的数据读取为键和列值的列表,才能得到正确的逻辑?
我无法得到正确的逻辑,请给我一些帮助。
collections.Counter
或collections.defaultdict
可以帮助进行计数。 - user2357112