[英]how to turn one set with 5 elements into 5 sets each with one element in python?
Lets say I have 2 sets of lists.假设我有 2 组列表。
set1 = [2, 4, 6, 8, 10]
set2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
From here I've tried to subtract set1 from set2 in order to get [1, 3, 5, 7, 9]
, and I've done so by saying print [x for x in set2 if x not in set1]
The output is just set2
, because there is only one element in set 2, and that is the list of all natural numbers up to and including 10.从这里开始,我尝试从 set2 中减去 set1 以获得
[1, 3, 5, 7, 9]
,我这样做是通过说 print [x for x in set2 if x not in set1]
输出只是set2
,因为在集合 2 中只有一个元素,那就是所有自然数的列表,包括 10。
So my question is how do I turn [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
into [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]
?所以我的问题是如何将
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
变成[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]
?
I know this is a basic question, but I'm new and I couldn't find any other questions like this.我知道这是一个基本问题,但我是新手,找不到任何其他类似的问题。 Please answer with answers that help in general and not only in this situation.
请回答对一般情况有帮助的答案,而不仅仅是在这种情况下。 Thanks in advance.
提前致谢。
You can try this:你可以试试这个:
s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_s = [[i] for i in s]
Output:输出:
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
you can use sets to solve the stated problem您可以使用集合来解决所述问题
set1 = [2, 4, 6, 8, 10]
set2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
set(set2) - set(set1)
Out[18]: {1, 3, 5, 7, 9}
the list comprehension works too, did you have a different result?列表理解也有效,你有不同的结果吗?
[e for e in set2 if e not in set1]
Out[17]: [1, 3, 5, 7, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.