问题
I want to cast set in list to list like below.
before: [(1, 1, 1), (1, 1, 0), (1, 0, 1)]
after: [[1, 1, 1], [1, 1, 0], [1, 0, 1]]
I need the as simple code as possible.
回答1:
>>> x = [(1, 1, 1), (1, 1, 0), (1, 0, 1)]
>>> list(map(list, x))
[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
Explanation
map(list, x)
takes an iterable x
and applies function list
to each element of this iterable. Thus the tuple (1, 1, 1)
becomes the list [1, 1, 1]
, (1, 1, 0)
becomes [1, 1, 0]
and (1, 0, 1)
becomes [1, 0, 1]
.
These lists are then stored in a map
object (assuming Python 3.x). A map
object is an iterator, which can be converted to a list by calling list
on it, as shown above. Often, though, you don't need to make this explicit conversion because iterator allows you to traverse the elements directly:
>>> for elem in map(list, x):
... print(elem)
...
[1, 1, 1]
[1, 1, 0]
[1, 0, 1]
回答2:
Let's define "before" as a variable called "array". Then we take the for-loop of the "array" while casting each element to a list.
array = [(1,1,1), (1,1,0), (1,0,1)]
casted_array = []
for tuples in array:
casted_array.append(list(tuples))
There are slightly easier ways to do this, but they are harder to understand. Explanation: You define the list [(1,1,1), (1,1,0), (1,0,1)] as a variable and then define a "dummy" variable called "casted_array". You then loop through the items in the "array" variable while saving them to the "tuples" iteration variable. Every time the iteration cycle loops, the sets/tuples are converted into lists and then added on to the "casted_array" variable. The casted set/tuple is now stored in the "casted_array" variable.
来源:https://stackoverflow.com/questions/53442777/how-to-cast-set-in-list-into-list-in-python