如果我的文本文件包含:
['A','B','C',21,'25','D','6','8','100','A'] ['Q','W' ,'E',21,'11','R','T',3,60,'C']
我希望从每个列表中收集第一项到python-例如:A和Q.我该怎么做?
我可能想稍后收集第3个值,例如C和E
以下编辑: 我现在有以下代码:
def ADMIN():
print("Welcome")
ADMINoption = input("Do you want option A or B.\n").upper()
if ADMINoption == 'A':
import re
file = open('Membership.txt').read()
temp = [re.split("\W+", i)[1:-1] for i in re.findall("\[(.*?)\]", file)]
list_of_members = [i[0] for i in temp]
print("The following are the usernames of the Members:")
#print (*list_of_members) THE * removes [] from list display
for a in list_of_members:
print (a)
ADMINchoice=input("Select the member details you wish to inspect\n").upper()
ADMIN()
它产生以下内容:
"Welcome Do you want option A or B. a
The following are the usernames of our members:
DON21
BAR50
Select the member details you wish to inspect"
我的文字文件包含: ['DON21','DONALD','TRUMP',21,'GYM','X','Easy',5,100,'PO'] ['BAR50','BARACK','OBAMA',50, '游泳','K','训练',3,60,'L']
如何从列表中获取相关值的问题答案? 例如,如果我选择'DON21',它将返回: ['DON21','DONALD','TRUMP',21,'GYM','X','Easy',5,100,'PO'] 甚至可以选择“TRUMP”,21,'GYM'等列表 ??
答案 0 :(得分:4)
你可以试试这个:
d = [['A', 'B', 'C', 21, '25', 'D', '6', '8', '100', 'A'], ['Q', 'W', 'E', 21, '11', 'R', 'T', 3, 60, 'C']]
s = [i[0] for i in d]
输出:
['A', 'Q']
访问文本文件中的数据:
import re
data = open('filename.txt').read()
new_data = [re.split("\W+", i)[1:-1] for i in re.findall("\[(.*?)\]", data)]
final_data = [i[0] for i in new_data]