[英]How do I make a selection from a text file based on what text is inside it (Python)
I am having trouble with my file. 我的档案有问题。 I've split it so each line is a separate list eg. 我将其拆分,因此每一行都是单独的列表,例如。
myList = [['Adam','16','Yes'], ['Fred','22','No']]
and trying to make a variable that only select lines with contain a "Yes". 并尝试制作一个仅选择包含“是”的行的变量。
How would I go about doing this? 我将如何去做呢?
因此,您只想选择第三个成员等于"Yes"
:
selected = [data for data in your_list if data[2] == "Yes"]
myList = your_input_sequence myList = your_input_sequence
lambda function to select only matching text: lambda x: x[<position_of_string_to_compare>].lower()
lambda函数,仅选择匹配的文本: lambda x: x[<position_of_string_to_compare>].lower()
Desired function: 所需功能:
result = filter(lambda x: x[2].lower() == 'yes', myList) 结果=过滤器(lambda x:x [2] .lower()=='是',myList)
>>> myList
[['Adam', '16', 'Yes'], ['Fred', '22', 'No']]
>>> res = filter(lambda x: x[2].lower()=='yes', myList)
>>> res
[['Adam', '16', 'Yes']]
You can do this: 你可以这样做:
myList = [['Adam','16','Yes'], ['Fred','22','No']]
x='Yes'
list1=[]
for i in myList:
for j in i:
if x==j:
list1.append(i)
for x in list1:
a=" ".join(x)
f= open("textDocument.txt","w+")
f.write(a)
c=f.read()
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.