我使用以下代码首先检查是否存在'('在字符串中。 如果是这样,我想将字符串分成两个,如下面的例子
['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']
['(Class 6)', '(0-60, 4yo+) (1m4f50y)', '1m4f Standard','(1m4f50y)']
但出于某种原因,如果我运行以下代码:
if details[1].count('(') == 2:
details = details[1].rsplit('(', 1)
我得到了
['(Class 6)', ['(0-60, 4yo+)', '1m4f50y)'], '1m4f Standard']`
我希望
['(Class 6)', '(0-60, 4yo+)', '1m4f Standard','(1m4f50y)']
答案 0 :(得分:2)
rsplit()
会返回一个列表,您将其放入details
。如果您获取该列表的第一个元素[0]
并将其放入您从details[1]
获取数据的元素中,那么您应该得到您期望的结果。
if details[1].count('(') == 2:
splitdata = details[1].rsplit('(', 1)
details[1] = splitdata[0]
details.extend(splitdata[1:])
答案 1 :(得分:0)
这有点像你想要做的吗?
deets = [
['(Class 6)', '(0-60, 4yo+) (1m4f50y)', '1m4f Standard', '(1m4f50y)']
]
def separate_tuples(details: list) -> list:
# Loop over each string in the list, but also get it's index
for index, string in enumerate(details):
# If the string has more than one tuple, remove it,
if string.count('(') == 2:
details.remove(string)
# but keep using the removed string for the following:
# separate it into parts
for part in string.split(')', 1):
# clear whitespace from either side
part = part.strip()
# if the part already exists in the list, get rid of the duplicate
if part in details:
details.remove(part)
# if the part doesn't end in a paren, add one and insert it at the current index
# otherwise, just add the part with no extras
details.insert(index, part + ')' if not part.endswith(')') else part)
# Move the current item to the back of the list
details.append(details.pop(index))
return details
for deet in deets:
print(separate_tuples(deet))
输出
['(Class 6)', '(0-60, 4yo+)', '1m4f Standard', '(1m4f50y)']