Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse strings into overlapping pairs with Python [duplicate]

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?

like image 792
HSskillet Avatar asked Oct 17 '25 01:10

HSskillet


1 Answers

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.

like image 159
Thierry Lathuille Avatar answered Oct 18 '25 13:10

Thierry Lathuille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!