【问题标题】:i need to replace digits in list alphabet starting from index key_m in alphabet of digits in list m_b by index in list c1我需要用列表 c1 中的索引替换列表字母表中的数字,从列表 m_b 中数字字母表中的索引 key_m 开始
【发布时间】:2022-01-18 23:11:51
【问题描述】:

我需要将列表字母表中的数字从列表 m_b 中数字字母表中的索引 key_m 开始替换为列表 c1 中的索引

from operator import setitem

def replace():

alphabet = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'],
        ['g'], ['h'], ['i'], ['j'], ['k'], ['l'],
        ['m'], ['n'], ['o'], ['p'], ['q'], ['r'],
        ['s'], ['t'], ['u'], ['w'], ['v'], ['x'],
        ['y'], ['z']]

key_m = 10
c1 = [17, 10, 21, 22, 1]

m_b = [['y'], ['a'], ['#'], ['b'], ['o'], ['i'],
       ['c'], ['d'], ['e'], ['f'], ['g'], ['h'],
       ['j'], ['k'], ['l'], ['m'], ['n'], ['p'],
       ['q'], ['r'], ['s'], ['t'], ['u'], ['v'],
       ['w'], ['x'], ['z'], ['_'], ['-'], ['!'],
       ['?'], ['$'], ['/'], ["@"], ['+'], ['%']]

for b, c in zip(c1, m_b):
    setitem(alphabet, b, c)

print(alphabet)

预期结果是字母 = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], [' g'], ['h'], ['i'], ['j'], ['p'], ['g'], ['t'], ['u'], ['a' ], ['p'], ['q'], ['r'], ['s'], ['t'], ['u'], ['w'], ['v'], ['x'],['y'], ['z']]

但实际结果是alphabet = [['a'], ['o'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h'], ['i'], ['j'], ['a'], ['l'], ['m'], ['n'], [' o'], ['p'], ['q'], ['y'], ['s'], ['t'], ['u'], ['#'], ['b' ], ['x'], ['y'], ['z']]

【问题讨论】:

  • 预期结果是什么?
  • ... 而实际结果呢?您遇到的具体问题是什么?欢迎来到 SO。请务必阅读How to Ask
  • 预期结果是字母 = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']、['h']、['i']、['j']、['p']、['g']、['t']、['u']、[' a'], ['p'], ['q'], ['r'], ['s'], ['t'], ['u'], ['w'], ['v' ], ['x'],['y'], ['z']]
  • edit你的帖子添加预期的输出?
  • 为什么是列表而不是长字符串?

标签: python list replace


【解决方案1】:

使用循环迭代c1 值,包裹enumerate 以增加索引(从key_m 开始)然后设置值

key_m = 10
c1 = [17, 10, 21, 22, 1]
for idx, value in enumerate(c1, start=key_m):
    alphabet[idx] = m_b[value]

我认为使用一维列表和字符串会更好

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'v', 'x', 'y', 'z']

m_b = 'ya#boicdefghjklmnpqrstuvwxz_-!?$/@+%'

key_m = 10
c1 = [17, 10, 21, 22, 1]
for idx, value in enumerate(c1, start=key_m):
    alphabet[idx] = m_b[value]

print(alphabet)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'p', 'g', 't',
# 'u', 'a', 'p', 'q', 'r', 's', 't', 'u', 'w', 'v', 'x', 'y', 'z']

【讨论】:

  • @IxDante 您可能需要一分钟,以确保此 2d 列表是强制性的,1 值列表在大多数情况下是个坏主意,请看我的编辑
  • yooo 我怎么联系你我想给你看我的代码和算法,如果可以的话?
  • @IxDante pastebin.com 使用它,但我只需花几分钟时间看一下,不再;)
  • 抱歉解决了,谢谢,但我刚解决了 2 个小问题,我的项目已经完成,你能帮帮我吗?
  • 如果key_m = 24如何让代码返回索引[0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 2020-12-01
  • 2018-12-23
  • 2019-04-25
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
相关资源
最近更新 更多