使用Python进行元组和列表操作。短切元组生成
在我的家庭作业中,我一直在思考这个问题 一切正常,但当使用Python进行元组和列表操作。短切元组生成,python,list,variables,tuples,Python,List,Variables,Tuples,在我的家庭作业中,我一直在思考这个问题 一切正常,但当p中有空格(')时。我需要停止创建can的过程 例如,如果我提交: rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')]) 我希望: ['C D', 'AB'] 返回,而不是像现在这样只返回[] 代码如下: def rankedVote(p,cs): candsplit = zip(*cs) cand = candspl
p
中有空格('
)时。我需要停止创建can
的过程
例如,如果我提交:
rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
我希望:
['C D', 'AB']
返回,而不是像现在这样只返回[]
代码如下:
def rankedVote(p,cs):
candsplit = zip(*cs)
cand = candsplit[0]
vote = list(p)
ppl = vote
can = list(p)
for i in range(len(vote)):
if ' ' in vote[i-1]:
return []
else:
vote[i] = int(vote[i])
can[vote[i]-1] = cand[i]
for i in range(len(vote)):
for j in range(len(vote)):
if i != j:
if vote[i] == vote[j]:
return []
return can
编辑:
在示例中:
rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
这意味着第一个,AB
变为第二个,
第二个cd
变为第一个,
它应该停止,因为第三个不存在
假设它不是2144
,而是2143
。
这意味着第三个EFG
将是第四个,
第四个
HJ K
将是第三个。代码按照您的指示执行。请看下面的代码块:
if ' ' in vote[i-1]:
return []
我想说,代码是按照你的指示执行的。请看下面的代码块:
if ' ' in vote[i-1]:
return []
我知道这个问题很老,但我觉得很有趣 就像前面所说的,到目前为止,您没有返回列表,您返回的是
[]
你应该做的是:
if ' ' in vote[i]:
return can[:i]
此外,由于您似乎知道如何使用zip
,您也可以这样做:
def rankedVote(p,cs):
cand = zip(*cs)[0]
# get elements before ' '
votes = p.split()[0] # '21'
# map votes index order with corresponding list order
# (number of `cands` is determined by length of `votes`)
cans = zip(votes, cand) # [('2', 'AB'), ('1', 'C D')]
# Sort the results and print only the cands
result = [can for vote, can in sorted(cans)] # ['C D', 'AB']
return result
输出:
>> rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
['C D', 'AB']
>> rankedVote("2143", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
['C D', 'AB', 'HJ K', 'EFG']
我知道这个问题很老,但我觉得很有趣 就像前面所说的,到目前为止,您没有返回列表,您返回的是
[]
你应该做的是:
if ' ' in vote[i]:
return can[:i]
此外,由于您似乎知道如何使用zip
,您也可以这样做:
def rankedVote(p,cs):
cand = zip(*cs)[0]
# get elements before ' '
votes = p.split()[0] # '21'
# map votes index order with corresponding list order
# (number of `cands` is determined by length of `votes`)
cans = zip(votes, cand) # [('2', 'AB'), ('1', 'C D')]
# Sort the results and print only the cands
result = [can for vote, can in sorted(cans)] # ['C D', 'AB']
return result
输出:
>> rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
['C D', 'AB']
>> rankedVote("2143", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
['C D', 'AB', 'HJ K', 'EFG']
我知道,但是我一直在想把什么放在这个代码块中,这样它就可以把所有东西都返回到空间之前。我知道,但是我坚持在这个代码块中放什么,这样它就可以把所有东西都返回到空间之前。你能用文字描述吗,确切地说,
rankedVote
的每个参数的每个部分意味着什么,函数应该输出什么,输出内容的各个部分意味着什么?你能用语言描述一下,rankedVote
的每个参数的每个部分的确切意思,以及函数应该输出什么,输出的部分意味着什么?