我有一个包含重复元素的列表:
list_a=[1,2,3,5,6,7,5,2]
tmp=[]
for i in list_a:
if tmp.__contains__(i):
print i
else:
tmp.append(i)
Run Code Online (Sandbox Code Playgroud)
我已经使用上面的代码来查找重复的元素list_a.我不想从列表中删除元素.
但我想在这里使用for循环.通常C/C++我们这样使用我猜:
for (int i=0;i<=list_a.length;i++)
for (int j=i+1;j<=list_a.length;j++)
if (list_a[i]==list_a[j])
print list_a[i]
Run Code Online (Sandbox Code Playgroud)
我们如何在Python中使用这样的?
for i in list_a:
for j in list_a[1:]:
....
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的代码.但它解决方案有误.我不知道如何增加价值j.
我试图找到最近5年没有重复数字,我一直得到错误 'int' object has no attribute '__getitem__'
这是我的代码,我到目前为止 - 我无法弄清楚它有什么问题.任何解释如何解决它是值得赞赏的.
def find_year():
start = 2015
years = []
while len(years) < 5:
if start[0] == start[1]:
return False
elif start[0] == start[2]:
return False
elif start[0] == start[3]:
return False
elif start[1] == start[2]:
return False
elif start[1] == start[3]:
return False
elif start[2] == start[3]:
return False
else:
years.append(start)
start -= 1
else:
print years
find_year()
Run Code Online (Sandbox Code Playgroud)