如何逐行读取文本文件并将奇数行分配给字典的键,将偶数行分配给字典的值?例如,我如何制作以下新行分隔列表:
A
B
C
D
E
F
G
H
进入这样的字典:
dict{"A":"B","C":"D","E":"F","G":"H"}
答案 0 :(得分:3)
with open(filename, 'r') as f:
d = {}
for line in f:
d[line.strip()] = next(f, '').strip()
注意:如果您的文件具有奇数行,则您的最后一个键将具有空值。如果您希望抛出异常,请将next(f, '')
更改为next(f)
。如果您希望使用其他默认更改next(f, '')
到next(f, 'default')
。
另一种方式:
with open(filename, 'r') as f:
d = {k.strip():v.strip() for k, v in zip(f, f)}
请注意,如果文本文件的行数为奇数,则会删除最后一个键。
当存在奇数行时保留最后一个键:
from itertools import izip_longest, imap
with open(filename, 'r') as f:
f = imap(str.strip, f)
d = dict(izip_longest(f, f, fillvalue='default'))
答案 1 :(得分:-1)
实际上,你只需要读入一个文件并循环遍历它。如果一行是奇数,请记住它作为值,如果一行甚至将其附加到字典中,并将该行作为键。
public static void main(String[] args) {
//deck of cards created
String[] cards = {"Ace of Spades","2 of Spades","3 of Spades",
"4 of Spades","5 of Spades","6 of Spades","7 of Spades",
"8 of Spades","9 of Spades","10 of Spades","Jack of Spades",
"Queen of Spades","King of Spades","2 of Diamonds",
"3 of Diamonds","4 of Diamonds", "5 of Diamonds","6 of Diamonds",
"7 of Diamonds","8 of Diamonds","9 of Diamonds","10 of Diamonds",
"Ace of Diamonds","Jack of Diamonds","Queen of Diamonds",
"King of Diamonds","Ace of Hearts","2 of Hearts","3 of Hearts",
"4 of Hearts", "5 of Hearts","6 of Hearts","7 of Hearts",
"8 of Hearts","9 of Hearts","10 of Hearts","Jack of Hearts",
"Queen of Hearts","King of Hearts","Ace of Clubs","2 of Clubs",
"3 of Clubs","4 of Clubs","5 of Clubs","6 of Clubs","7 of Clubs",
"8 of Clubs","9 of Clubs","10 of Clubs","Jack of Clubs",
"Queen of Clubs","King of Clubs"};
Random rand = new Random();
boolean isRunning = true;
int draw = 0;
int count = 0;
int unique = 0;
String temp = "a";
//set up drawing method
while(isRunning = true){
while(draw < 4 ){
temp = cards[rand.nextInt(52)];
draw++;
}
count ++;
if( cards.equals(temp)){
isRunning = false;
}
System.out.println(count);
}
System.out.println("Number of draws: " + count);