I everyone,
I struggle to convert an array of array like this :
JavaScript
x
7
1
[
2
["foo","bar","foo","bar","foo"],
3
["foo","bar","foo","bar","foo"],
4
["foo","bar","foo","bar","foo"],
5
["foo","bar","foo","bar","foo"]
6
]
7
to an array of tuples (array
, str
) like this:
JavaScript
1
7
1
[
2
(["foo","bar","foo","bar","foo"], "type1"),
3
(["foo","bar","foo","bar","foo"], "type1"),
4
(["foo","bar","foo","bar","foo"], "type1"),
5
(["foo","bar","foo","bar","foo"], "type1")
6
]
7
I did find a way to append the type to the array but it’s not exactly what I want:
JavaScript
1
7
1
[
2
["foo","bar","foo","bar","foo", "type1"],
3
["foo","bar","foo","bar","foo", "type1"],
4
["foo","bar","foo","bar","foo", "type1"],
5
["foo","bar","foo","bar","foo", "type1"]
6
]
7
Do you have something better ? Thanks :)
Advertisement
Answer
Solution
Shortest solution: list(zip(vals, types))
🔥🔥🔥
JavaScript
1
17
17
1
vals = [
2
["foo","bar","foo","bar","foo"],
3
["foo","bar","foo","bar","foo"],
4
["foo","bar","foo","bar","foo"],
5
["foo","bar","foo","bar","foo"]
6
]
7
8
# If you must specify different types for each element
9
# uncomment the following line
10
# types = ['type1', 'type2', 'type3', 'type4']
11
12
# If all of them should have the same type
13
types = ['type1' for _ in range(len(vals))]
14
15
# Finally combine vals and types
16
list(zip(vals, types))
17
Output:
JavaScript
1
5
1
[(['foo', 'bar', 'foo', 'bar', 'foo'], 'type1'),
2
(['foo', 'bar', 'foo', 'bar', 'foo'], 'type1'),
3
(['foo', 'bar', 'foo', 'bar', 'foo'], 'type1'),
4
(['foo', 'bar', 'foo', 'bar', 'foo'], 'type1')]
5