Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法更改由文件行组成的列表中的元素?_Python_List_File - Fatal编程技术网

Python 有没有办法更改由文件行组成的列表中的元素?

Python 有没有办法更改由文件行组成的列表中的元素?,python,list,file,Python,List,File,我有一个写在文件中的书籍列表,每本书都是一个单独的行,它有多个属性除以,最后一个属性为True或False,在将其写入列表后,使用 list_of_books = open('books'.txt').read().split() 我必须将“真”改为“假”,反之亦然, 有办法吗 列表示例 ['qwe,rty,1999,1231231231234,Drama,1000,1,True', 'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 't

我有一个写在文件中的书籍列表,每本书都是一个单独的行,它有多个属性除以,最后一个属性为True或False,在将其写入列表后,使用

list_of_books = open('books'.txt').read().split()
我必须将“真”改为“假”,反之亦然, 有办法吗

列表示例

['qwe,rty,1999,1231231231234,Drama,1000,1,True',
 'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
 'tui,fgh,2009,4564564564567,Horror,900,5,True']

如果您知道布尔值总是在末尾,那么您可以简单地更改字符串的内容,如下所示:

exampleList = ['qwe,rty,1999,1231231231234,Drama,1000,1,True',
               'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
               'tui,fgh,2009,4564564564567,Horror,900,5,True']

#Change the second element in the list from True to False
listElement = exampleList[1]
exampleList[1] = listElement[:-4] + "False"

print(exampleList)
或者,您可以使用split来完成此操作

exampleList = ['qwe,rty,1999,1231231231234,Drama,1000,1,True',
               'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
               'tui,fgh,2009,4564564564567,Horror,900,5,True']

listElement = exampleList[1].split(",")
listElement[-1] = "False"
exampleList[1] = listElement

print(exampleList)

您正在尝试更改文件中的数据吗?是的,有一种方法可以做到这一点。这其实很简单,我甚至敢说是微不足道的。您尝试过哪些不起作用的内容?提示:使用split',将每个字符串转换为较大列表中自己的列表考虑使用csv模块读取您的文件。更新名单是一件容易的事;将这些更改反映到原始文件是另一个问题;解析输入有什么问题吗?这是一种简单的方法。简单,但不必要的脆弱。还有其他更健壮的解决方案,不涉及任意字符串切片。如果最后4个字符不是真的,您仍然会替换它们,而不是失败。请使用链接解释此代码是如何工作的,不要只给出代码,因为解释更有可能帮助未来的读者。另见。
exampleList = ['qwe,rty,1999,1231231231234,Drama,1000,1,True',
               'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
               'tui,fgh,2009,4564564564567,Horror,900,5,True']

listElement = exampleList[1].split(",")
listElement[-1] = "False"
exampleList[1] = listElement

print(exampleList)