Python supports a concept called "list comprehensions".
Following is sample example (written in Python syntax)
A = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
print( [ a + [i] for a in A for i in range(1, 4) if i in a] )
[[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3], [2, 3, 4, 2], [2, 3, 4, 3], [3, 4, 5, 3]]
What's the most natural way to translate this Python code to Mathematica? I have the following method:
A = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}};
Select[Table[ a ~ Join ~ {i}, {a, A}, {i, 3}] ~ Flatten ~ 1,
MemberQ[ Most @ #, Last @ #]&]
but I think it's neither fast nor elegant, therefore I am looking for a better way.
Answer
This one is very close to your Python code
Join @@ Table[Append[a, i], {a, A}, {i, Intersection[Range[3], a]}]
{{1, 2, 3, 1}, {1, 2, 3, 2}, {1, 2, 3, 3}, {2, 3, 4, 2}, {2, 3, 4, 3}, {3, 4, 5, 3}}
Comments
Post a Comment