1

与えられたような文字列の場合、これを文字列"RL2R'F2LD'"に分割する最も効率的な方法は何"R" "L2" "R'" "F2" "L" "D'"ですか?最初にそれらを個々の文字に分割し、次にそれらをリストに追加しようとするなど、いくつかの方法を試しましたが、何も正しく機能しませんでした。

4

4 に答える 4

5
def rubikstring(s):
    import string
    cumu = ''
    for c in s:
        if c in string.ascii_letters:
            if cumu: yield cumu
            cumu = ''
        cumu += c
    if cumu: yield cumu

could do your job. With

>>> for i in rubikstring("RL2R'F2LD'"): i
...
'R'
'L2'
"R'"
'F2'
'L'
"D'"

you get your desired result, with

>>> list(rubikstring("RL2R'F2LD'"))
['R', 'L2', "R'", 'F2', 'L', "D'"]

as well.

于 2012-11-07T15:37:21.180 に答える
4

You could use a regular expression:

import re
cubedirs = re.compile(r"[RLFBUDrlfbudxyz][2']?")
cubedirs.findall("RL2R'F2LD'")

This outputs ['R', 'L2', "R'", 'F2', 'L', "D'"].

The regular expression is actually very simple. The [..] character group means: match one character from the set given (so an R, or an L, or an F, etc.).

Then we look for a second character group optionally matching 1 character, namely a 2 or '. The question mark after the second character is what makes it optional; we are specifying that it's also fine if the ' or the 2 character is not there.

The .findall() method simply returns all matches that have been found, so you get a list of all character groups in the input string that match the pattern.

于 2012-11-07T15:37:28.503 に答える
3

正規表現を使用できます。

[FBUDLRfbudlrxyz][2']?

これがライブデモです。

import re

s = "RL2R'F2LD'"

for m in re.finditer("[FBUDLRfbudlrxyz][2']?", s):
    print m.group(0)

(コメントでそれを行う方法を説明していないことをお詫びします、私は本当にPythonを知りません。)

于 2012-11-07T15:38:59.430 に答える
1

コメントしたように、正規表現は良い方法です:

>>> import re
>>> re.findall('[A-Z]{1}[0-9]{0,1}', "RL2R'F2LD'")
['R', 'L2', 'R', 'F2', 'L', 'D']
于 2012-11-07T15:38:53.680 に答える