0

我有一个包含一组字符串和另一个动态列表的列表:

arr = ['sample1','sample2','sample3']
applist=[]

我正在逐行读取文本文件,如果一行以 arr 中的任何字符串开头,则将其附加到 applist,如下所示:

for line in open('test.txt').readlines():
    for word in arr:
        if line.startswith(word):
            applist.append(line)

现在,如果我在 arr 列表中没有任何字符串,那么我想将“NULL”附加到 applist。我试过了:

for line in open('test.txt').readlines():
    for word in arr:
        if line.startswith(word):
            applist.append(line)
        elif word not in 'test.txt':
            applist.append('NULL')

但它显然不起作用(它插入了许多不必要的 NULL)。我该怎么做?此外,除了以 arr 中的字符串开头的三行之外,文本文件中还有其他行。但我只想附加这三行。提前致谢!

4

2 回答 2

1
for line in open('test.txt').readlines():
  found = False
  for word in arr:
    if line.startswith(word):
        applist.append(line)
        found = True
        break
  if not found: applist.append('NULL')
于 2013-05-16T01:45:26.663 回答
0

I think this might be what you are looking for:

found1 = NULL
found2 = NULL
found3 = NULL
for line in open('test.txt').readlines():
  if line.startswith(arr[0]):
     found1 = line;
  elif line.startswith(arr[1]):
     found2 = line;
  elif line.startswith(arr[2]):
     found3 = line;
  for word in arr:

applist = [found1, found2, found3]

you could clean that up and make it better looking, but that should give you the logic you're going for.

于 2013-05-16T02:28:59.000 回答