-1

假设我有两个 csv 输出,如下所示:

标记1:

[['a', '', '', '', '', ''], ['b', '', '', '', '', ''], ['c', '' , '', '', '', ''], ['d', '', '', '', '', ''], ['e', '', '', '', ' ', ''], ['f', '', '', '', '', ''], ['g', '', '', '', '', '']]

标记2:

[['a', '10', '', '', '', ''], ['b', '', '', '', '', ''], ['c', ' 10', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '7', '', ' ', '', ''], ['m', '9', '', '', '', ''], ['n', '', '', '', '', '' ]]

在这种情况下,在第一个 csv 输出中找不到 m 和 n。所以我为找出这两个而编写的代码是:

标记1[行][0] != 标记2[行1][0]:

            print 'some marks are not the same - no match found'

上面的代码不起作用。

有没有什么具体的方法可以解决这个问题?

谢谢。

4

4 回答 4

3

我将首先说我投票支持@ThaneBrimhall 的答案,但为了展示各种方式(并假设您只关心一个元素是否在另一个元素中,无论位置如何):

# Get a set of unique first elements for each list
set1 = set([n[0] for n in mark1])
set2 = set([n[0] for n in mark2])

# Items in mark1 but not mark2
if set1.difference(set2):
  print 'some marks are not the same - no match found'

# Items in mark2 but not mark1
if set2.difference(set1):
  print 'some marks are not the same - no match found'

如果您想查看哪些导致错误:

# Get a set of unique first elements for each list
set1 = set([n[0] for n in mark1])
set2 = set([n[0] for n in mark2])

# Items in mark1 but not mark2
set1_diffs = set1.difference(set2)
if set1_diffs:
  print 'Marks {0} in mark1 but not mark2'.format(list(set1_diffs))

# Items in mark2 but not mark1
set2_diffs = set2.difference(set1)
if set2_diffs:
  print 'Marks {0} in mark2 but not mark1'.format(list(set2_diffs))
于 2012-08-21T05:03:27.823 回答
2

我发现这样做的最简单(并且计算速度最快)的方法是执行以下操作:

if [n for n in mark2 if n[0] not in [m[0] for m in mark1]]:
    print 'some marks are not found...'

需要两个 for 循环来比较您要迭代的每个值。上面的代码大致翻译为:

keys = []
for m in mark1:
    keys.append(m[0])
for n in mark2:
    if n not in keys:
        print 'some marks not found...'
        break
于 2012-08-21T04:02:47.117 回答
0

鉴于您想比较整个列表列表,这应该比较它们:

 if mark1 != mark2:
      print 'some are not the same...'

如果您只想比较列表中每个列表的第一个字段,这就是这样做的方法。

def compare_first(mark1,mark2):
  for row in mark1:
    for row2 in mark2:
      if row[0] != row2[0]:
        return false;
  return true

然后主要使用该功能

if !equal_firs(mark1,mark2):
  print('some are not the same...')
于 2012-08-21T04:01:33.667 回答
0

你的例子没有多大意义。

mark1= [['a', '', '', '', '', ''], ['b', '', '', '', '', ''], ['c', '', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '', '', '', '', ''], ['f', '', '', '', '', ''], ['g', '', '', '', '', '']]
mark2= [['a', '10', '', '', '', ''], ['b', '', '', '', '', ''], ['c', '10', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '7', '', '', '', ''], ['m', '9', '', '', '', ''], ['n', '', '', '', '', '']]
if mark1[row][0] != mark2[row1][0]:
    print 'some marks are not the same - no match found'

在那个 if 语句中,您正在处理 row 和 row1 - 为什么您不在同一行中查找?

除此之外,这是不正确的-

mark1[row][0] != mark2[row1][0]:

我相信你的意思是:

if mark1[row][0] != mark2[row1][0]:
于 2012-08-21T04:02:12.037 回答