简体   繁体   English

如何调整我的代码以仅删除打印所需的值

[英]How can i adjust my code to remove print desired values only

My current code:我目前的代码:

def write_from_dict(users_folder):
    for key, value in value_dict.items():  # iterate over the dict
        file_path = os.path.join(users_folder, key + '.txt')
        with open(file_path, 'w') as f:       # open the file for writing
            for line in value:                # iterate over the lists

                f.write('{}\n'.format(line))

My current output:我目前的输出:

['4802', '156', '4770', '141']
['4895', '157', '4810', '141']
['4923', '156', '4903', '145']

My desired output:我想要的输出:

4802,156,4770,141
4895,157,4810,141
4923,156,4903,145

so basically i want the spaces '' and [] removed.所以基本上我想删除空格 '' 和 [] 。

Replace代替

f.write('{}\n'.format(line))

With

f.write('{}\n'.format(",".join(line)))

At the moment, line is a list of ints , we need to print a string which is the result of concatenating each integer (as strings) togethere with commas.目前, line是一个ints list ,我们需要打印一个字符串,它是将每个整数(作为字符串)用逗号连接在一起的结果。

This can be done really easily with the str.join method which takes an iterable of strings and then joins them together with a deliminator - which will be a comma ( ',' ) here.这可以通过str.join方法轻松完成,该方法采用可迭代的字符串,然后使用分隔符将它们连接在一起 - 此处将是逗号( ',' )。

So, the f.write line should be something like:所以, f.write行应该是这样的:

f.write('{}\n'.format(''.join(str(i) for i in line)))

or if the elements of line are already strings (it is impossible to tell from your current code), then you can use the more simple:或者如果line的元素已经是字符串(从您当前的代码中无法判断),那么您可以使用更简单的:

f.write('{}\n'.format(''.join(line)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM