【问题标题】:Having issues with a conditional comparing a list and a string有条件比较列表和字符串的问题
【发布时间】:2023-02-14 12:30:26
【问题描述】:
def decode(message):
    message = message.split(" ")
    a = code.a
    for xd in range(len(message)):
        if a == message[xd]:
            message[xd] = 'a'
    return message

code.a 从另一个文件导入一个值为“b”的变量,另一个文件看起来像

a = "b"

然后我使用 decode("b") 得到 b 而不是 a 的输出

我想得到一个输出

【问题讨论】:

  • 这里的 code 是什么?
  • 代码是我用变量导入文件的方式
  • 欢迎来到堆栈溢出!改掉使用for index in range(len(list)): 的习惯。使用for item in list:for index, item in enumerate(list):
  • 如果我们提供提示,您也可以这样做:message.replace(code.a, 'a') 并返回变量,但是嘿,人们尝试实现自己的东西,大多数时候是从中学习,或者在其他地方再次实现它。

标签: python python-3.x string list if-statement


【解决方案1】:

您的脚本有效:

from types import SimpleNamespace
code = SimpleNamespace(a='b')
print(code)
>>> namespace(a='b')
print(code.a)
>>> b
decode('b')
>>> ['a']

您应该得到类型列表的输出。我使用简单的命名空间来模拟你的code.a = 'b'。你确定code.a是你想的那样吗?因为看起来 code.a 不是 'b' 或者不是字符串?

【讨论】:

  • 这不回答这个问题,它应该是一个评论。
  • 我像这样导入了变量 import code_1 as code
【解决方案2】:

我使用你的代码:

def decode(message):
    message = message.split(" ")
    a = 'b'                      # instead of code.a, I use 'b' directly
    for xd in range(len(message)):
        if a == message[xd]:
            message[xd] = 'a'
    return message

decode("b")
#['a']

【讨论】:

  • 这不回答这个问题,它应该是一个评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2014-06-28
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多