任务是加载一个文件,其中包含一些具有不同答案数的问题,并且第一个列出的答案始终是正确答案
e.g:
Who is Jane?
Girl
Boy
Both
Why are we here?
Because
For fun
所以我在想我会把数据读入一个数组,但最后我需要能够为每个问题调整答案(并以某种方式保持正确的答案),然后将问题改组。 / p>
因此,如果我将数据读入数组,它将如下所示:
a = ['Who is Jane?', 'Girl', 'Boy', 'Both', 'Why are we here?', 'Because', 'For fun']
现在我想我必须要做的事情最好将数组拆分成包含始终问题及其所有答案的较小数组。 所以我会有像
这样的东西test = [['Who is Jane?', 'Girl', 'Boy', 'Both'], ['Why are we here?', 'Because', 'For fun']]
任何人都知道我怎么能这样做?
我知道要访问问号,您可以使用a[0][-1]
,这会从'Who is Jane'
给您一个问号。
答案 0 :(得分:2)
这是我的实施,也许你的更好。
>>> a = ['Who is Jane?', 'Girl', 'Boy', 'Both', 'Why are we here?', 'Because', 'For fun']
>>>
>>> def fun(x):
... y = []
... for i in x:
... if i.endswith('?') and y:
... yield y
... y = []
... y.append(i)
... else:
... yield y
...
>>> list(fun(a))
[['Who is Jane?', 'Girl', 'Boy', 'Both'], ['Why are we here?', 'Because', 'For fun']]
答案 1 :(得分:0)
以下是一种可能算法的概述,假设lines
包含来自文本文件的行,并且它们已经过适当的预处理:
result = []
group = [lines[0]]
for line in <lines from the second element to the last>:
if <line ends with a question mark>:
# append group to result
# reset group to an empty list
# append line to group
这个想法只是遍历行列表,每当遇到问题时创建一个新列表,并将前一个列表附加到整个结果中。
根据您所选择的课程,提高您解决问题的能力(如找到上述算法)比完全学习Python(或任何语言)更重要。