简体   繁体   English

如何根据文本文件中的文本进行选择(Python)

[英]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.

相关问题 Python - 如何在文本文件中制作字典? - Python - How do I make a dictionary inside of a text file? 我需要做什么/学习才能使基于文本的Python游戏可供互联网用户访问 - What do I need to do/learn to make my text based Python game accessible to users over the internet 给定一个文本文件,如何在Python中将其制成字典? - Given a text file, how do I make it into a dictionary in Python? 在Python中,如何将基于扩展名的文件名从文本文件中拉出并放入新的文本文件中? - In Python, how do I pull the file name based on extension out of a text file and place in new text file? 如何使用 input() 从文本文件中获取输入数据的 python 的代码? - How do I make the code of python which get the input data from a text file with using input()? 如何从文本文件的列表中创建列表? - How do I make a list in a list from a text file? Python,如何从另一个文本文件中的文本中删除文本? - Python, How do I Remove Text From a Text From That's in Another Text File? Python如何从文本文件制作可执行文件 - Python how to make an executable from a text file 如何使用python从文本文件中创建字典 - How to make a dictionary from a text file with python 如何使用python正则表达式从文件中获取文本 - How do I grab text from a file using python regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM