[英]I try to make a new set that it find the elements common between the two sets and subtract them with for and if without using different set method
I try to make a new set that it find the elements common between the two sets and subtract them with for and if without using different set method我尝试创建一个新集合,它找到两个集合之间的共同元素,并用 for 和 if 减去它们而不使用不同的集合方法
I was going to compare all the elements in my first set and second set by opening two different for loops and using if command, find the common ones and remove them with the remove command, but I am getting the "list index out of range" error我打算通过打开两个不同的 for 循环并使用 if 命令来比较第一组和第二组中的所有元素,找到常见的元素并使用 remove 命令删除它们,但我得到“列表索引超出范围”错误
my code is below.我的代码在下面。 I don't know much coding as I am beginner.我不太了解编码,因为我是初学者。 I wrote this code for practice我写这段代码是为了练习
my_set = {1,2,3,4,5}
your_set = {4,5,6,7,8,9,10}
my_list = list(my_set)
your_list = list(your_set)
for i in range(len(my_list)):
for j in range(len(your_list)):
if (my_list[i] == your_list[j]):
my_list.remove(my_list[i])
my_set2 = set(my_list)
print(my_set2)
If you want to remove the common items in my_set
and your_set
from my_set
.如果你想从my_set
中删除my_set
和your_set
中的公共项。
my_set = {1, 2, 3, 4, 5}
your_set = {4, 5, 6, 7, 8, 9, 10}
new_set = my_set.difference(your_set.intersection(my_set))
print(new_set)
print(my_set)
# {1, 2, 3}
# {1, 2, 3, 4, 5}
If you want the difference removed from your_set
,如果你想从your_set
中删除差异,
your_new_set = your_set.difference(your_set.intersection(my_set))
You can also do it using if
and for
as in your original code,您也可以像在原始代码中那样使用if
和for
来执行此操作,
result = [] # Initialize an empty list to store the result
# Iterate through each element in my_set
for i in my_set:
# Check if the current element is not in your_set
if i not in your_set:
# If it is not, append it to the result list
result.append(i)
# if you want output in set, convert the list back to set
result = set(result)
# Print the final result
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.