在列表中迭代字符串并将其连接到前面的字符串(如果字符串满足条件)

2024-05-18 19:55:47 发布

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

我有一个由许多字符串组成的列表,这些字符串在'\n'被拆分。但是,在原始文本文件本身中,在条目的中间插入了一些换行符,这使事情变得混乱。你知道吗

我想遍历列表并询问第一个字符是否等于'r''i'。如果没有,我想将该字符串与前面的字符串连接起来。

这是我当前列表的摘录:

[‘rs386834028,46662406,1,No summary provided.,http://www.snpedia.com/index.php/Rs386834028(CA;CA)', 'rs121909207,94480221,1,"common in clinvar', '",http://www.snpedia.com/index.php/Rs121909207(C;C)']

列表中的第一个元素是我希望列表中所有元素的样子。我希望第二个和第三个连接在一起,看起来像这样:

[‘rs386834028,46662406,1,No summary provided.,http://www.snpedia.com/index.php/Rs386834028(CA;CA)', 'rs121909207,94480221,1,"common in clinvar,http://www.snpedia.com/index.php/Rs121909207(C;C)']

这就是我的代码现在的样子:

import io
def readSNP(filename1):
    f = io.open(filename1, mode='r', encoding='utf8')
    fileAsOneString = f.read()
    splitList = fileAsOneString.split('\n')
    for string in splitList:
        for i in range(len(string)):
            if (i[0] =! 'r' or i[0] =! 'i'):

这就是我被困住的地方。任何帮助/建议将不胜感激!你知道吗


Tags: no字符串incomhttp列表indexwww
1条回答
网友
1楼 · 发布于 2024-05-18 19:55:47

您只需遍历列表和pop(),并将不匹配的值连接到上一项。你知道吗

i = 0
while i < len(lst):
    if not (lst[i].startswith('i') or list[i].startswith('r')):
        lst[i - 1] += lst.pop(i)
    else:
        i += 1

相关问题 更多 >

    热门问题