【问题标题】:replace the first occurrence of a string element in list [duplicate]替换列表中第一次出现的字符串元素[重复]
【发布时间】:2018-10-30 18:31:45
【问题描述】:

对于列表中字符串的每个元素,我需要将第一次出现的1 更改为0,但这会改变一切:

a, b = input().split()
a = int(a)
d=[]
for x in range(1,a+1):
    globals()['side%s' % x] = input("Enter something: ")
    d.append(globals()['side%s' % x])

d = [s.replace('1', '0') for s in d]


print(d)

例子:

4 1 // 4 number of inputs, 1 - number of possible changes to string

0101
0010
0100
1000

需要

0001
0000
0000
0000

【问题讨论】:

  • 你能更好地解释你想要达到的目标吗?
  • 如果我理解正确,您只想用0 替换第一次出现的1 并保持其他出现不变?
  • 是的,每个项目只出现一次
  • @Bad.coder 这是stackoverflow.com/questions/4628618/… 的副本。答:replace() 采用可选的第三个参数,即替换的最大次数。例如,replace('1', '0', 1) 将仅对第一个实例执行替换

标签: python string list


【解决方案1】:

由于您希望替换 x 的出现次数,因此替换函数提供了此 string.replace(s, old, new[, maxreplace]),您可能希望将 b 作为第三个参数传递给 maxreplace

a, b = input().split()
a = int(a)
d=[]
for x in range(1,a+1):
    globals()['side%s' % x] = input("Enter something: ")
    d.append(globals()['side%s' % x])

d = [s.replace('1', '0', int(b)) for s in d] # maxreplace will be b only


print(d)

【讨论】:

    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多