我有一个由许多字符串组成的列表,这些字符串已在'\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'):
这就是我被卡住的地方。任何帮助/建议将不胜感激!
答案 0 :(得分:0)
您可以遍历列表并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