【问题标题】:How to relate an array of integers to an array of strings in the code?如何将整数数组与代码中的字符串数组相关联?
【发布时间】:2020-02-25 15:00:18
【问题描述】:

我是一名 Python 初学者,开始熟悉 pymc 库。在我的程序中,我生成 1 到 100 之间的随机数。当我生成随机变量时,它显然会返回一个包含整数的数组(在本例中为 10 int 数组):

customer_names = customer_names.random(size=10)

这个帖子的历史是我想通过一个表把每个int变量和一个特定的名字联系起来,好像每个名字都有一个标识符,但是我不知道如何在代码中实现。

我想要的是当我 print(customer_names) 而不是得到数组 [ 54 2 45 75 22 19 16 34 67 88] 时,我想要得到 [ Jose Maria Carmen Alejandro Davinia Eduardo Carlos Fátima Marc Mireia]

我尝试了以下方法:

def identificar_nombres(nc = customer_names):
    for i in range (0, 9): #in this case 9 because I'm generating 10 random numbers
        if nc[i] == '1':
            return 'ANTONIO' 
        elif nc[i] == '2':
            return 'MARIA CARMEN'
        else: return nc[i] # process repeatedly with all names in the name dataset

nombres = identificar_nombres(customer_names) 

但没有结果。

谢谢!

【问题讨论】:

  • 你可以做什么创建一个名称字典,例如这个字典 = {"1": 'ANTONIO', "2": "MARIA CARMEN"} 等,然后使用从字典中访问名称字典[str(nc[i)]
  • @RishabhBatra 非常感谢,另一个愚蠢的事情,如何将随机数数组转换为由字典转换为名称的数组?
  • 我找到了,问题已解决;)@RishabhBatra

标签: python python-3.x pymc


【解决方案1】:

使用字典(键值对)来存储变量,如下所示:

variables = {1: 'ANTONIO', 2: 'MARIA CARMEN'}

然后像这样访问它:

customer_names = list(variables.values()))
print(customer_names)

输出:

['ANTONIO', 'MARIA CARMEN']

【讨论】:

  • 非常感谢 Suman,这只是另一个愚蠢的疑问,但如果我有一个包含 10 个随机数的整数数组,我们可以称它为“array_indicators”。如何使用该字典将该数组转换为具有字典值的另一个称为“名称数组”的数组(在这种情况下,“值”是名称)
  • 我找到了,问题已解决;)
【解决方案2】:

通过“没有结果”,我假设您得到的是 else 语句。

这是因为使用 if nc[i] == '1' 您将 class 'int' 与永远不会匹配的 class 'str' 进行比较。试试下面的代码:

if nc[i] == 1:
            return 'ANTONIO' 

或者,在这里使用字典(键值)将是更好的方法。

【讨论】:

    【解决方案3】:
    def identificar_nombres(customer_names):
      customerlist = []
      for i in customer_names:
          if customer_names[i] == 1:
              customerlist.append("ANTONIO") 
          elif customer_names[i] == 2:
              customerlist.append("MARIA")
      return customerlist
    
    nombres = identificar_nombres(customer_names) 
    print(nombres)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 2018-05-29
      • 1970-01-01
      相关资源
      最近更新 更多