我有一本字典 -
$ cat infile
string 2 2 3 3 1 4
other 5 1 20 9 3 7
$ ./sorttuples infile
string 1 4 2 2 3 3
other 3 7 5 1 20 9
我想以这种格式将其写入文本文件 -
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
这是我目前的代码 -
Dave
Male
96
Alice
Female
98
然而,它在文本文件中产生以下输出:
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open("dictionary.txt", 'w') as f:
for key, value in d.items():
f.write('%s \n %s \n' % (key, value))
我该怎么调整呢? 请帮忙!感谢。
答案 0 :(得分:2)
使用格式转换 public static void scanner() {
System.out.println("Is this a real scenario? Please enter 'Yes' or 'No'.");
Scanner scan = new Scanner(System.in);
String answer;
answer = scan.nextLine();
//for (int x = 0; x < 2; x++ ) {
if (answer.equals("Yes") || answer.equals("yes")) {
real();
} else if (answer.equals("No") || answer.equals("no")) {
hypothetical();
} else {
System.out.println("Please enter 'Yes' or 'No'.");
answer = scan.nextLine();
}
}
}
到tuple
时,您会获得元组的表示,这是(大致有2种方法{{1}实际上当你str
控制台中的项目时,python会打印什么。
要获取没有元组装饰的元素,您必须解压缩元组。一个选项(使用__str__
):
__repr__
print
将format
的元素解包为2个元素。剩下的就是for key, value in d.items():
f.write("{}\n{}\n{}\n".format(key,*value))
更紧凑的方法是将格式字符串乘以3(减少复制/粘贴)
*
答案 1 :(得分:1)
我使用i in range
方法迭代每个键中的每个值 -
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open("dictionary.txt", 'w') as f:
for key, value in d.items():
for x in range(0,2):
f.write('%s \n %s \n' % (key, value[x]))
答案 2 :(得分:1)
以下适用于Python 3.6:
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open('dictionary.txt', mode='w') as f:
for name, (sex, age) in d.items():
f.write(f'{name}\n{sex}\n{age}\n')
您可以在for
循环顶部解包元组。此外,在Python 3.6中,您可以使用f-string机制直接将变量值插入字符串。
答案 3 :(得分:0)
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open("dictionary.txt", 'w') as f:
for key in d.keys():
f.write('%s \n' % (key))
for v in d[key]:
f.write('%s \n' % (v))