## Pythonic方法修改列表中包含特定数字（不仅仅是字符）的元素内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (43)

``````input = '3xy+y-2x+2xy'
``````

``````Var = ['xy', 'y', 'x']
Coe = ['+5', '+1', '-2']
``````

``````[(e[0]+e[2:]) if (e[1]== '1' and e[2].isalpha() ) else e for e in IR ]
``````

``````def simplify(poly):

#If the first coefficient is positive, then I add a + for calculation later on
if poly[0] !='-':
poly = '+'+poly
L = list(poly)

#Put each monomial in a list as an element
Temp, e = [], ''
for i in L:
if i != '+' and i != '-':
e += i
else:
Temp.append(e)
e = ''
e += i

#The last one will be left out and the first one will be None
Temp.append(e)
Temp.pop(0)

#If the monomial only has a + or - in front of it, then give it a '1' so it's easier for calculation
SortAndGiveOne = [''.join(e[0] + '1' + e[1:]) if not e[1].isdigit() else e for e in Temp]

#Try to get letters from each element of the list
Var = [''.join(sorted(i for i in e if i.isalpha())) for e in SortAndGiveOne]
#Try to get coefficients from each element of the list
Coe = [''.join(i for i in e if not i.isalpha()) for e in SortAndGiveOne]

#Calculation of equivalent monomials
newvar = []
newcoe = []
for va, co in zip(Var, Coe):
try:
ind = newvar.index(va)
newcoe[ind] = str(int(newcoe[ind]) + int(co))
except ValueError:
newvar.append(va)
newcoe.append(co)

# Put the new lists together
Put_t = list(map(lambda x,y : y + x, newvar, newcoe))

# Add the plus sign as it will be gone if there was calculation involved.
FinalSign = ['+'+ e if e[0] != '+' and e[0] != '-' else e for e in Put_t]

#Delete the elements with 0 as coefficient
Delete0 = [e for e in FinalSign if not e[1]=='0']

#Change the +1 and -1 coefficients to + and -
Change1 = [(e[0]+e[2:]) if (e[1]== '1' and e[2].isalpha() ) else e for e in Delete0 ]

#Sort the list based on length and then lexi order
FS_sort = sorted(Change1, key = lambda s: (len(''.join(filter(str.isalpha, s))), (''.join(filter(str.isalpha, s)))))

#Join together as a list
JT = ''.join(FS_sort)

if JT[0] == '+':
JT = JT[1:]

return JT
``````

### 2 个回答

``````import re
newlist = [re.sub('(?<=[+-])1(?=[A-Za-z])', '', e) for e in your_list]
``````

``````k = ['5xy', '+1y', '-2x', '-1xy', '+11xy']
newlist = [re.sub('(?<=^[+-])1(?=[A-Za-z])', '', e) for e in k]
>>> newlist
['5xy', '+y', '-2x', '-xy', '+11xy']
``````

``````IR = ['5xy', '51y', '-2x']
result = [(e[0]+e[2:]) if (e[1]== '1' and e[2].isalpha() ) else e for e in IR ]
print(result)
``````

``````['5xy', '5y', '-2x']
``````

``````def transform(e):
multiplier = ''.join(c for c in e if c.isnumeric())
return e[0] + e[2:] if multiplier == '1' else e

IR = ['5xy', '51y', '-2x']
result = [transform(e) for e in IR]
print(result)

IR = ['5xy', '+1y', '-2x']
result = [transform(e) for e in IR]
print(result)
``````

``````['5xy', '51y', '-2x']
['5xy', '+y', '-2x']
``````