I'm new to Python, and I'm trying to make a sudoku solver. Now, I need to check if a number in a candidates list is in another list, and if it is, delete it from the candidates list.
line1 = [6,6,6,6]
def checkline(x):
candidates = [1,2,3,4]
if any(number in x for number in candidates):
crap = int in x and candidates
print(crap)
candidates.remove(crap)
print ("Works")
print(candidates)
x = line1. I want "crap" to be the common number. How do I do it?
与其从列表中删除它,不如考虑使用过滤后的项目创建一个新列表:
candidates = [i for i in candidates if i not in line1]
I don't exactly understand the logic in your code but here is how you can "check if a number in a candidates list is in another list, and if it is, delete it from the candidates list":
candidates = [1, 2, 3, 4]
another_list = [1, 4, 5, 6, 7 ,8, 9]
for index, candidate in enumerate(candidates):
if candidate in another_list:
del candidates[index]
After running the code above, candidates will be [2, 3]
.
For completeness (from a learning perspective), the code above can also be written without enumerate
, like so:
candidates = [1, 2, 3, 4]
another_list = [1, 4, 5, 6, 7 ,8, 9]
for candidate in candidates:
if candidate in another_list:
candidates.remove(candidate)
This is not the best way of approaching this problem but I thought it'll be easier for you to understand what the logic required is then you should re-think how you're solving this. At the least, using Python's list comprehensions (instead of the for
statements above) would be of great help here:
candidates = [1, 2, 3, 4]
another_list = [1, 4, 5, 6, 7 ,8, 9]
candidates = [candidate for candidate in candidates if candidate not in another_list]
Is this helpful?
Pehaps, you need something like this:
def checkline(line1,candidates):
buf=[]
for crap in candidates:
if crap not in line1:
buf.append(crap)
return buf
candidates=checkline(line1,candidates)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.