我有一个文本文件,如下所示:
100 Spam
250 Spam
50 Spam
20 Eggs
70 Eggs
现在,我想将这些行合并到一个新文件中,使其看起来像这样:
300 Spam
90 Eggs
我逐行将文件读入列表。现在,我像这样遍历列表中的每个项目:
new_list = []
j = 1
for i in range(len(old_list)):
new_list.append("")
if old_list[i][4:] == old_list[i-j][4:]:
new_list[i-j][:4] = str(int(old_list[i][:4].strip()) + int(old_list[i-j][:4].strip())).ljust(4)
new_list[i-j][4:] = old_list[i-j][4:]
j += 1
else:
new_list[i-j] = old_list[i-j]
我遇到了两个问题:
我是编程新手,所以也许有更好的方法可以同时解决所有问题?
答案 0 :(得分:0)
此解决方案仅限于您提供的输入。 作为第一种幼稚的方法,我将问题分为三个部分:
old_list
,其中每个元素都是一个元组(值,键)old_list = [(100, 'Spam'), (250, 'Spam'), (50, 'Spam'), (20, 'Eggs'), (70,'Eggs')]
result = {}
for elem in old_list:
if elem[1] in result:
result[elem[1]] += elem[0]
else:
result[elem[1]] = elem[0]
对于old_list
中的每个元素,如果您已经看到具有相同键的项,则对其值求和并继续。否则,将密钥添加到具有当前值的结果字典中。
result = {'Spam': 400, 'Eggs': 90}
祝你好运!
答案 1 :(得分:0)
尝试一下:
public class Task10 extends Application {
@Override
public void start(Stage primaryStage) {
HBox hbox5 = new HBox();
VBox VBoxAll = new VBox();
Image gifs[] = new Image[3];
gifs[0] = new Image(this.getClass().getResource("/img/L1.gif").toExternalForm());
gifs[1] = new Image(this.getClass().getResource("/img/L2.gif").toExternalForm());
gifs[2] = new Image(this.getClass().getResource("/img/L1.gif").toExternalForm());
ImageView currentGif = new ImageView();
Button localLoadButton = new Button("Start!");
localLoadButton.setOnAction(e -> {
show(currentGif, gifs);
});
hbox5.getChildren().addAll(currentGif, localLoadButton);
VBoxAll.getChildren().addAll(hbox5);
VBoxAll.setSpacing(15);
Pane pane = new Pane();
pane.getChildren().add(VBoxAll);
Scene scene = new Scene(pane, 500, 350);
primaryStage.setScene(scene);
primaryStage.show();
}
public void show(ImageView currentGif, Image[] gifs) {
for (int i = 0; i<gifs.length; i++) {
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, e -> { currentGif.setImage(gifs[i]); }),
new KeyFrame(Duration.seconds(2), e -> { currentGif.setImage(null); })
);
timeline.play();
}
}
}
答案 2 :(得分:0)
result = {}
with open("your_file.txt") as infile:
for line in infile:
amount, food_item = line.split()
result[food_item] = result.get(food_item, 0) + int(amount)
print(result) # {'Spam': 400, 'Eggs': 90}
然后您可以将result
写到新文件中
with open("some_other_file.txt") as outfile:
for food_item, amount in result.items():
outfile.write(f"{amount} {food_item}\n")