python-3.x - Python 3.x | 如何删除列表中的括号和撇号以获得更清晰的输出
问题描述
这是到目前为止的代码:
dictionary={'i':'prep', 'og':'konj', 'om':'prep', 'som':'subj', 'på':'prep', 'til':'prep', 'en':'determ', 'av':'prep'}
'''Get a list of keys from dictionary which has the given value'''
def getKeysByValue(dictionary, valueToFind):
listOfKeys = list()
listOfItems = dictionary.items()
for item in listOfItems:
if item[1] == valueToFind:
listOfKeys.append(item[0])
return listOfKeys
print()
'''Get list of keys with value prep'''
listOfKeys = getKeysByValue(dictionary, 'prep')
prep = 'preposisjoner'
print(f"It is {len(listOfKeys)} {prep} in the dictionary.")
print('They are:')
print()
'''Iterate over the list of keys'''
for key in listOfKeys:
print(key,end=', ')
print(), print()
def wrap_by_word(s, n):
'''returns a string where \\n is inserted between every n words'''
a = s.split()
ret = ''
for i in range(0, len(a), n):
ret += ' '.join(a[i:i+n]) + '\n'
return ret
print()
x = wrap_by_word(str(listOfKeys), 2)
print(x)
我得到的输出是这样的:
它是字典中的 5 个前置词。
他们是:
i, om, på, til, av,
['i', 'om',
'på', 'til',
'av']
我想要的是这样的输出:
i, om
på, til
av
任何帮助将不胜感激。>
解决方案
假设您获得的输出列表被命名为 x ,如您的代码中所述。将以下代码添加到现有代码中。
x = ['i', 'om', 'på', 'til','av']
print(' '.join(x))
# You will get this below as your final output:
i om på til av
推荐阅读
- html - 如何使 Bootstrap 表中的嵌套表不继承父 Bootstrap“表”类?
- java - 在 JAVA 中重构 JSON 文件
- python - 从两个数据文件中提取唯一行
- xtext - Xtext 和 XBase 的语法限制 JVMModelInferrer 继承
- python - ImageMagick 未授权将 PDF 转换为图像
- go - go channel 读取并发和阻塞
- android-studio - 如何使用 Kotlin 从 Google Drive 获取信息?
- java - 更新 firebase 中的一些数据,并在同一个“父级”中保持其他数据不变
- python - 广度优先搜索优化
- c# - 电子商务的通用管理面板如何做