【问题标题】:Errors with apostrophes and lists撇号和列表的错误
【发布时间】:2018-06-22 17:38:37
【问题描述】:

我正在尝试将括号插入到由通过.extend() 放在一起的两个列表组成的列表的开头和结尾,因此它的打印如下:('dog','cat','mouse')('pig, 'cow', 'sheep')。但是我得到的输出是'dog', 'cat', 'mouse', 'pig', 'cow', 'sheep'。虽然您可以通过多种方式插入括号——"("chr(40) 等)——但明显的缺陷是括号输出为引号。

.join 我知道可以用于整个列表。但是,我还没有找到一种方法可以将它用于一个项目——这种方法存在吗?

我的代码如下所示:

all_animals= []
house_animals= ['dog','cat','mouse']
farm_animals= ['pig', 'cow', 'sheep']
all_animals.extend(house_animals)
all_animals.extend(farm_animals)
print(str(all_animals)[1:-1])

编辑

类似地,如果 字典 具有撇号 (') [请注意:它进入列表] 输出会受到影响,因为它会在引号 ("") 中打印该特定单词而不是正常的撇号。示例: living_beings= {"Reptile":"Snake's","mammal":"whale", "Other":"bird"} 如果您使用以下代码(我需要):

new= []
for i in living_beings:
    r=living_beings[i]
    new.append(r)

那么输出是“snake's”、“whale”、“bird”(注意第一个输出和其他输出的区别)。所以我的问题是:如何停止影响输出的撇号。

【问题讨论】:

    标签: python arrays python-3.x list dictionary


    【解决方案1】:

    您可以将列表转换为元组,然后在打印之前将它们放入列表中:

    house_animals = ['dog','cat','mouse']
    farm_animals = ['pig', 'cow', 'sheep']
    all_animals = [tuple(house_animals), tuple(farm_animals)]
    
    print(''.join(str(x) for x in all_animals))
    

    输出:

    ('dog', 'cat', 'mouse')('pig', 'cow', 'sheep')
    

    替代解决方案更接近您的方法,但使用 append

    all_animals= []
    house_animals= ['dog','cat','mouse']
    farm_animals= ['pig', 'cow', 'sheep']
    all_animals.append(house_animals)
    all_animals.append(farm_animals)
    print(''.join(str(tuple(x)) for x in all_animals))
    

    输出:

    ('dog', 'cat', 'mouse')('pig', 'cow', 'sheep')
    

    编辑

    这正是 Python 表示字符串的方式:

    >>> "snake's"
    "snake's"
    >>> "whale"
    'whale'
    

    它与字典或列表无关。

    你的例子:

    living_beings= {"Reptile":"Snake's","mammal":"whale", "Other":"bird"} 
    new= []
    for i in living_beings:
        r=living_beings[i]
        new.append(r)
    

    你可以格式化字符串来去掉引号:

    print('[{}]'.format(', '.join(new)))
    
    [Snake's, whale, bird]
    

    【讨论】:

      【解决方案2】:

      首先考虑将farm/house_animals 添加为list,而不是单独添加每个动物:

      all_animals = []
      all_animals.append(house_animals)
      all_animals.append(farm_animals)
      

      那么你要找的打印语句可以是这样的:

      print(''.join(['{0}'.format(tuple(animal)) for animal in all_animals]))
      

      【讨论】:

        【解决方案3】:

        另一种方法可以是:

        "".join(
             [str(tuple(house_animals)), str(tuple(farm_animals))]
        )
        

        输出:

        ('dog', 'cat', 'mouse')('pig', 'cow', 'sheep')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-08
          相关资源
          最近更新 更多