Python 如何调整代码以仅删除所需的打印值
我当前的代码:Python 如何调整代码以仅删除所需的打印值,python,python-3.x,Python,Python 3.x,我当前的代码: 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
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))
我的当前输出:
['4802', '156', '4770', '141']
['4895', '157', '4810', '141']
['4923', '156', '4903', '145']
我的期望输出:
4802,156,4770,141
4895,157,4810,141
4923,156,4903,145
因此,基本上我希望删除空格“”和[]。替换
f.write('{}\n'.format(line))
与
目前,
行
是一个列表
中的整数
,我们需要打印一个字符串,它是将每个整数(作为字符串)与逗号连接在一起的结果
使用str.join
方法可以很容易地实现这一点,该方法接受一个iterable字符串,然后用一个除数将它们连接在一起,除数在这里是一个逗号(,“
)
因此,f.write
行应该类似于:
f.write('{}\n'.format(''.join(str(i) for i in line)))
或者,如果line
的元素已经是字符串(无法从当前代码中分辨),则可以使用更简单的:
f.write('{}\n'.format(''.join(line)))
尝试将最后一行更改为:
f.write('{}\n'.format(“,”.join(map(str,line)))
可能的重复项您不必将这些元素转换为字符串吗?看起来它们可能基于示例输出,但也可能是int
s。OP没有具体说明。
f.write('{}\n'.format(''.join(line)))