【问题标题】:How can I convert a range of ints to strings to be used for variables?如何将一系列整数转换为用于变量的字符串?
【发布时间】:2017-12-22 07:10:02
【问题描述】:

所以我有一些在字符串末尾使用数字的变量。但是当我使用 str 函数时,“i”似乎没有转换为字符串。知道为什么会这样吗?

代码:

has_GroupConnection1 = True
has_GroupConnection2 = True
has_GroupConnection3 = True

GroupConnection1 = 45
GroupConnection2 = 88
GroupConnection3 = 55

for i in range(1,3):
    if str(has_GroupConnection[i]) == True:
         print(str(GroupConnection[i]))

【问题讨论】:

标签: python variables range


【解决方案1】:

我知道你在尝试做什么,但你做不到(大部分情况见下文)。你写的代码去糖:

has_GroupConnection.__getitem__(i)
# foo[x] -> foo.__getitem__(x)

由于您的程序中没有定义has_GroupConnection,因此这将永远不会起作用,而是会抛出NameError。不过,你可以定义它。

has_GroupConnection = []
has_GroupConnection.append(None)  # 0th element
has_GroupConnection.append(True)  # 1st element
has_GroupConnection.append(True)  # 2nd element
has_GroupConnection.append(True)  # 3rd element
# or indeed has_GroupConnection = [None, True, True, True]
# or a dict will work, too...

# as above...
GroupConnection = [None, 45, 88, 55]

for i in range(1,3):  # note this is only [1, 2], not [1, 2, 3]
    if has_GroupConnection[i]:
         print(str(GroupConnection[i]))

我的第一句话过于简单化了,您可以使用evallocals(),但这是一个坏主意,所以我不会向您展示如何做到这一点,并且会强烈告诫你不要这样做!它丑陋、效率低下,而且代码味道很糟糕(你应该为自己考虑在谷歌上搜索它而感到羞耻!)

【讨论】:

  • @TomKarzes 已修复,不知道我在想什么。
【解决方案2】:

这是使用元组使用列表的另一种方式

group_connection = list()
group_connection.append((True, 45))
group_connection.append((True, 88))
group_connection.append((True, 55))

for i in range(0,len(group_connection)):
    if (group_connection[i][0] == True):
         print(str(i) + " has the connection number " + str(group_connection[i][1]))

输出

0 has the connection number 45
1 has the connection number 88
2 has the connection number 55

【讨论】:

    【解决方案3】:

    这就是你要找的东西:

    has_GroupConnection = [True] * 3
    GroupConnection = [45, 88, 55]
    
    for i in range(3):
        if has_GroupConnection[i]:
             print(GroupConnection[i])
    

    输出是:

    45
    88
    55
    

    has_GroupConnectionGroupConnection 现在都是列表,因此您可以使用 [] 对它们进行索引。我把循环改成从0跑到2,原来的循环从1跑到2,我也去掉了一些不必要的东西。

    【讨论】:

      【解决方案4】:

      这将是解决问题的“一种”方法。

      has_connections = [True, True, False]
      group_connections = [45, 88, 55]
      
      for h, g in zip(has_connections, group_connections):
          if h:
              print(g)
      

      【讨论】:

        【解决方案5】:

        我会考虑在此处使用字典来存储这些值(嵌套在“has”和“connection”属性中),这样您就可以毫无问题地循环访问这些键。

        如果您需要包含具体数字,请使用字符串替换:

        对于范围内的 i (1,3):

        while connection-dict['GroupConnection%s' % str(i)]['has']:

        print(dict['GroupConnection%s' % str(i)]['conn-number'])

        【讨论】:

          【解决方案6】:

          语法[] 用于指定可迭代对象中的元素,如列表或字符串,或从dict 中检索值。您正在尝试使用它来识别变量,但这不起作用。您可能应该使用dict,而不是:

          group_connections = {
              1 : None,
              2 : 45,
              3 : 88,
              4 : 55      
          }
          

          然后您可以遍历dict 的键来获取您所有的GroupConnections:

          for grp in group_connections:
              if group_connections[grp]:
                  print(group_connections[grp])
          

          或者你可以使用dict.items() 方法:

          for grp_number, connection in group_connections.items():
              if connection:
                  print(connection)
          

          由于您的两条数据是相关的,因此将它们放在一起更有意义,以便它们以某种方式相关。

          【讨论】:

            猜你喜欢
            • 2021-06-16
            • 1970-01-01
            • 2023-04-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-08
            • 2017-04-04
            • 2018-07-04
            相关资源
            最近更新 更多