【问题标题】:python write items prior to first matchpython在第一次匹配之前写入项目
【发布时间】:2014-10-28 04:24:49
【问题描述】:

我希望微调我编写的这个脚本。

我删除了 list0 中包含的 list1 中的所有项目。

但是我遇到了一个问题,我想在 list1 中找到与 list0 匹配的第一个项目,并创建一个包含 list0 中在初始匹配之前的项目的 list2。

例子:

list0 = ['#A', '77', 'TEST', 'ST']
list1 = ['77', 'MAIN', 'ST']

list2 = ['#A']

对于上面的例子,我的代码是这样写的:

list2 = ['#A', 'TEST']

谁能帮忙? -谢谢

import csv

address1_new = csv.writer(open('C:/Users/USR01/python/test1_new.csv', 'ab'))

with open('C:/Users/USR01/python/test1.csv', 'rb') as c:
    reader = csv.reader(c)

    for row in reader:

        address0 = [] #newline for file: *test1_new.csv*

        list0 = row[0].strip().split(' ')
        address0.append(row[0].strip())

        list1 = row[1].strip().split(' ')
        address0.append(row[1].strip())

        list2 = [x for x in list0 if x not in list1]
        address0.append(' '.join(list2))

        #address1_new.writerow(address0)

        print address0

【问题讨论】:

    标签: python list csv indexing


    【解决方案1】:

    使用 set():

    list0 = ['#A', '77', 'TEST', 'ST']
    list1 = ['77', 'MAIN', 'ST']
    list2 = list(set(list0) - set(list1))
    

    https://docs.python.org/2/library/sets.html

    【讨论】:

    • 返回:['TEST', '#A'] 这是我想要避免的。我想在第一场比赛之前获得所有项目。第一场比赛是'77' 所以给我['#A'] from list0
    【解决方案2】:

    我想通了:

    item1 = list1[0]
    
    if item1 in list0:
        idx = list0.index(item1)
        print list0[0:idx]
    

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多