首页 > 解决方案 > 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



任何帮助将不胜感激。>

标签: python-3.xdictionary

解决方案


假设您获得的输出列表被命名为 x ,如您的代码中所述。将以下代码添加到现有代码中。

x = ['i', 'om', 'på', 'til','av']
print(' '.join(x))

# You will get this below as your final output:

 i om på til av

推荐阅读