我是编码新手,对于如何处理我的伪代码感到困惑。 我正在定义第一个重复函数,对于 a = [1 2 2 3 4 4] 它返回 2,
def firstDuplicate(a):
# put first element into new list (blist)
# check second element to blist
# if same, return element and end
# else, try next blist element
# if no next element, add to end of blist
# do the same with third element (counter) and so on until end of list
alist = list(a)
blist = list(a[1])
bleh = 1
comp = 2
if list(a[comp]) == blist[bleh]:
return list(a[comp]) # and end
if else bleh = bleh+1 # and repeat til last blist element
# to stop?
else blist = blist+list(a[2]) # append outside of blist?
这就是我到目前为止所做的。有什么建议我下一步该怎么做吗?
如果我理解正确的话,您想在迭代列表时返回第二次出现的第一个数字。为了实现这一点,我将使用 set 并检查当前项目是否已在集合中,如果是则返回它,否则将项目添加到集合中。 (您也可以使用列表来做到这一点,但效率较低。)
def firstDuplicate(a):
set_ = set()
for item in a:
if item in set_:
return item
set_.add(item)
return None
如果您对列表理解的单行代码感兴趣
a = [10,34,3,5,6,7,6,1,2]
print [n for i , n in enumerate(a) if n in a[i+1:] and n not in a[:i]][0]
a = [1, 2, 2, 3, 4, 4,]
def find_it(look_here):
have_seen = set()
for item in look_here:
if item in have_seen:
return item
have_seen.add(item)
find_it(a)
2
zip
列表自身移动 1,filter
通过相等,选择第一项 (next
),并获取结果长度 2 元组的第一项。如果不存在重复项,则返回 None
(默认为 (None, None)
的 next
)。
next(filter(lambda x: x[0] == x[1], zip(a, a[1:])), (None, None))[0]