[英]Python 3.3: Split string and create all combinations
我使用的是Python 3.3。 我有這個字符串:
"Att education is secondary,primary,unknown"
現在我需要拆分最后三個單詞(可能有更多或只有一個)並創建所有可能的組合並將其保存到列表中。 像這兒:
"Att education is secondary"
"Att education is primary"
"Att education is unknown"
最簡單的方法是什么?
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(",")]
注意:如果逗號分隔值中間或值本身中有空格,則可能無效。
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
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]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.