【问题标题】:Python - List - string value changePython - 列表 - 字符串值变化
【发布时间】:2021-12-07 11:22:49
【问题描述】:

我有am = ['a:hull', 'b:2', 'c:3']的列表

我想拥有am = ['a:london', 'b:2', 'c:3'],方法是使用一个函数将hull 更改为london,而不更改其余部分。

我尝试am = {a:london},但它改变了整个列表,我想保持其他信息不变

任何帮助将不胜感激

【问题讨论】:

  • am[0] = "a:london"?
  • am = {a:london} 根本不会更改列表。它只是将一个全新的字典分配给名称am

标签: python list class format


【解决方案1】:

您可以使用索引访问列表项,更改项的方法相同。 如果您知道列表中项目的索引(位置),那么您可以这样做:

am[0] = "a:london"

其中 0 是项目的索引。

【讨论】:

  • 奇怪的是,当我使用 am[0] 时,我仍然得到完整列表 'a:hull', 'b:2', 'c:3' 但没有方括号(原始数据也有dtype:最后的对象)
【解决方案2】:

你可以使用python内置的replace()函数。

strings = ['a:hull', 'b:2', 'c:3']

new_strings = []

for string in strings:
    new_string = string.replace("a:hull","a:london")
 
    new_strings.append(new_string)

print(new_strings)

输出将是 ['a:london', 'b:2', 'c:3']

【讨论】:

  • 你为什么要创建一个新列表,而且要遍历整个列表,而不是只修改一个项目
猜你喜欢
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多