python - 撇号和列表错误

标签 python arrays python-3.x list dictionary

我试图在列表的开头和结尾插入括号,该列表由通过 .extend() 放置在一起的两个列表组成,因此它会像这样打印:('dog', '猫','老鼠')(' pig ,'牛','羊')。但是我得到的输出是 '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”(注意第一个和其他输出之间的区别)。所以我的问题是:如何停止影响输出的撇号。

最佳答案

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

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]

关于python - 撇号和列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48240139/

相关文章:

python - Python 中的 imgradient matlab 等价物

arrays - 将字符串参数传递给函数以访问数组的属性

c++ - 在数组中查找重复项

python - 测试字典键是否存在,不为空且不为空

python - tarfile compressionerror bz2 模块不可用

python - 在Conda环境中安装包,但只能在Python中运行而不是在iPython中运行?

python - 将两个图表重叠绘制

python - PyQt4 python 中的 "RuntimeError: maximum recursion depth exceeded while calling a Python object"错误

c - 结构数组段错误

python - 使用Scrapy爬取MIT OCW网站,但输出为空