Python 3.3: 拆分字符串并创建所有组合

3 投票
3 回答
550 浏览
提问于 2025-04-18 01:42

我正在使用Python 3.3。我有这样一个字符串:

"Att education is secondary,primary,unknown"

现在我需要把最后三个单词(可能还有更多,或者只有一个)分开,然后创建所有可能的组合,并把它们保存到一个列表里。就像这里:

"Att education is secondary"
"Att education is primary"
"Att education is unknown"

有没有简单的方法可以做到这一点?

3 个回答

2
s="Att education is secondary,primary,unknown".split()

w=s[1]
l=s[-1].split(',')

for adj in l:
    print(' '.join([s[0],w,s[2],adj]))

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

3
a = "Att education is secondary,primary,unknown"
last = a.rsplit(maxsplit=1)[-1]
chopped = a[:-len(last)]

for x in last.split(','):
    print('{}{}'.format(chopped, x))

如果你能确保你的文字之间只用一个空格分开,这种方法也能很好地工作(更优雅):

chopped, last = "Att education is secondary,primary,unknown".rsplit(maxsplit=1)
for x in last.split(','):
    print('{} {}'.format(chopped, x))

只要最后一个单词的分隔符不包含空格,这种方法就能正常工作。

输出:

Att education is secondary
Att education is primary
Att education is unknown
3
data = "Att education is secondary,primary,unknown"
first, _, last = data.rpartition(" ")
for item in last.split(","):
    print("{} {}".format(first, item))

输出

Att education is secondary
Att education is primary
Att education is unknown

如果你想把字符串放在一个列表里,可以在列表推导式中使用相同的方法,像这样

["{} {}".format(first, item) for item in last.split(",")]

注意:如果逗号分隔的值中间有空格,或者值本身有空格,这种方法可能就不管用了。

撰写回答