查找有序列表中的第一个重复元素
Finding the first duplicate element in an ordered list
我是编码新手,不知道如何处理我的伪代码。
我正在定义第一个重复函数,对于 a = [1 2 2 3 4 4] 它 returns 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?
这就是我到目前为止所做的。对我接下来要做什么有什么建议吗?
如果我没理解错的话,您想 return 在遍历列表时第二次出现的第一个数字。为此,我将使用 set 并检查当前项目是否已在集合中,如果是 return ,否则将项目添加到集合中。 (您也可以使用列表来做到这一点,但效率较低。)
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
我是编码新手,不知道如何处理我的伪代码。 我正在定义第一个重复函数,对于 a = [1 2 2 3 4 4] 它 returns 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?
这就是我到目前为止所做的。对我接下来要做什么有什么建议吗?
如果我没理解错的话,您想 return 在遍历列表时第二次出现的第一个数字。为此,我将使用 set 并检查当前项目是否已在集合中,如果是 return ,否则将项目添加到集合中。 (您也可以使用列表来做到这一点,但效率较低。)
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