如何在拆分更大的列表后访问列表[python]

2024-09-30 12:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串itemspecs,其中包括两个问题,用#@分隔,问题部分(问题、选项、答案…)用#分隔。我得用这根绳子做个测验

itemspecs = '''
question 1
Wie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?
##
Michiel de Ruyter
Piet Heijn
De zilvervloot is nooit door de Nederlanders onderschept
##
1
##
Answer B De Nederlandse vlootvoogd werd hierdoor bekend.
#@#
question 2
In welk land ligt Upernavik?
##
Antartica
Canada
Rusland
Groenland
Amerika
##
3
##
Answer D Het is een dorp in Groenland met 1224 inwoners.
'''

x = itemspecs.split('#@#')
for item in x:
    y = item.split('##')
    print(y)

但是当我运行这个并键入print(y[0])时,我得到了问题2的第一部分,这就是

question 2 In welk land ligt Upernavik?

但我如何才能达到问题1,即:

question 1
Wie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?

Tags: answerinisdequestionwasdiewie
3条回答

试试这个:first_question=itemspecs.split("#@#")[0].split("##")[0]

print(first_question)

question 1 Wie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?

干杯

翻译输入(deepl.com)

itemspecs = '''
question 1
Who was the Dutch shipowner who conquered the Spanish silver fleet?
##
Michiel de Ruyter
Pete Heijn
The silver fleet was never intercepted by the Dutch.
##
1
##
Answer B The Dutch fleet guardian became known as a result.
#@#
question 2
In which country is Upernavik located?
##
Antartics
Canada
Russia
Greenland
United States
##
3
##
Answer D It is a village in Greenland with 1224 inhabitants.
'''

测试代码(Python 3.6.3)

x = itemspecs.split('#@#')
for item in x:
    y = item.split('##')
    q = y[0].split('\n')  # Split lines; on Windows use '\r\n'
    q_ = list(filter(None, q))  # Remove empty lines
    print(q_)

输出

['question 1', 'Who was the Dutch shipowner who conquered the Spanish silver fleet?']
['question 2', 'In which country is Upernavik located?']

尝试将值附加到列表中,然后访问它

Ex:

x = itemspecs.split('#@#')
res = []
for item in x:
    res.append(item.split('##'))
print res[0][0]

输出:

question 1
Wie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?

相关问题 更多 >

    热门问题