I am new to Python and am attempting to parse a list of node paths into each pair presented in the path. For example:
I have a list (for nodes x, y, and z) that looks like this
list = ['xyzx', 'xzyx', 'zxyz', 'zyxz', 'yxzy', 'yzxy']
I am able to split each string at an arbitrary spot, but I need to split them into overlapping ordered pairs to get something like this:
newList = [('xy', 'yz', 'zx'), ('xz', 'zy', 'yx'), etc..]
or an individual list for each permutation would work as well:
newList1 = ['xy', 'yz', 'zx']
newList1 = ['xz', 'zy', 'yx']
etc..
Any ideas?
You can generate them with a list comprehension, as:
l = ['xyzx', 'xzyx', 'zxyz', 'zyxz', 'yxzy', 'yzxy']
[tuple(s[i:i+2] for i in range(len(s)-1)) for s in l]
# [('xy', 'yz', 'zx'), ('xz', 'zy', 'yx'),
# ('zx', 'xy', 'yz'), ('zy', 'yx', 'xz'),
# ('yx', 'xz', 'zy'), ('yz', 'zx', 'xy')]
Note that you should avoid naming your list "list", as this is a Python builtin function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With