为了从i中使用元素而分离列表时出现问题

2024-10-03 21:36:29 发布

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

我正试图打开一个文件并从该文件中获取第一个单词 然后比较是否是同一个词 i、 e.源索引.txt

TTTGATTAAT , source-document01012.txt , 0 , 9
TAATAGTTAG , source-document01012.txt , 6 , 15
TTAGTTTACT , source-document01012.txt , 12 , 21

获取TTTGATTAAT以便以后使用

从代码中提取

with open ('source_index.txt', 'r') as fsource:
    index1 = [line.strip().split(",") for line in fsource]

    with open ('susp_index.txt', 'r') as fsusp:
        index2 = [line.strip().split(",") for line in fsusp]

    if  index1[0] == index2[0]:

通过使用index1[0],它给出了整行。我做错什么了


Tags: 文件txtsourceforindexaswithline
2条回答

此代码

with open ('source_index.txt', 'r') as fsource:
    index1 = [line.strip().split(",") for line in fsource]

返回列表的列表

所以你应该尝试index[0][0]而不是index[0]

我不知道为什么你只需要第一行中的第一个单词,却要遍历整个文件

您只需执行以下操作:

  • 读第一行
  • 用“,”(空格和逗号)分开
  • 从那次拆分中得到第一个项目

代码如下:

with open ('source_index.txt', 'r') as fsource:
    index1 = fsource.readlines()[0].split(" ,")[0]
print(index1)

#TTTGATTAAT

相关问题 更多 >