用python创建一个fruit字典,其中内含有5种水果的每斤售价,Wartermelon:15、banana:20、Pineapple:25、Orange:12、Apple:18,请先打印此fruits字典,再依水果每斤售价降序排列打印。
时间: 2023-12-06 12:44:41 浏览: 29
可以按照以下方式创建和排序这个字典:
```python
# 创建字典
fruits = {'Wartermelon': 15, 'banana': 20, 'Pineapple': 25, 'Orange': 12, 'Apple': 18}
# 打印字典
print("Fruits dictionary:")
print(fruits)
# 降序排序并打印字典
print("\nFruits dictionary in descending order of price per kg:")
sorted_fruits = dict(sorted(fruits.items(), key=lambda item: item[1], reverse=True))
print(sorted_fruits)
```
输出结果为:
```
Fruits dictionary:
{'Wartermelon': 15, 'banana': 20, 'Pineapple': 25, 'Orange': 12, 'Apple': 18}
Fruits dictionary in descending order of price per kg:
{'Pineapple': 25, 'banana': 20, 'Apple': 18, 'Wartermelon': 15, 'Orange': 12}
```
相关问题
用Python编写以下程序(1)编写程序,要求键盘输入一串字符,输出其中出现最多的字符以及该字符出现的次数。(3) 创建一个fruit字典,其中内含有5种水果的每斤售价,Wartermelon:15、banana:20、Pineapple:25、Orange:12、Apple:18,请先打印此fruits字典,再依水果每斤售价降序排列打印。(4) 《红楼梦》人物统计。编写程序统计《红楼梦》中前20位出场最多的人物。
好的,我来一一回答你的问题:
关于第一个问题,以下是Python代码实现:
```
string = input("请输入一串字符:")
char_dict = {}
for char in string:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
max_char = max(char_dict, key=char_dict.get)
print("出现最多的字符是:", max_char)
print("该字符出现的次数是:", char_dict[max_char])
```
关于第二个问题,以下是Python代码实现:
```
fruits = {
"Watermelon": 15,
"Banana": 20,
"Pineapple": 25,
"Orange": 12,
"Apple": 18
}
print("原始字典:", fruits)
sorted_fruits = sorted(fruits.items(), key=lambda x: x[1], reverse=True)
print("按水果每斤售价降序排列后的字典:", dict(sorted_fruits))
```
关于第三个问题,这是一个比较复杂的问题,需要先对《红楼梦》进行文本处理,提取出人物名称,再进行统计。以下是Python代码实现:
```
import re
# 读取《红楼梦》文本内容
with open("红楼梦.txt", encoding="utf-8") as f:
content = f.read()
# 使用正则表达式提取出人物名称
pattern = re.compile(r"[\u4e00-\u9fa5]{2,4}(?:·[\u4e00-\u9fa5]{2,4})*")
names = pattern.findall(content)
# 统计人物出现次数
name_dict = {}
for name in names:
if name in name_dict:
name_dict[name] += 1
else:
name_dict[name] = 1
# 按出现次数降序排列,并取前20位
sorted_names = sorted(name_dict.items(), key=lambda x: x[1], reverse=True)
top20_names = sorted_names[:20]
# 打印前20位人物及其出现次数
print("《红楼梦》前20位出场最多的人物:")
for name, count in top20_names:
print(name, count)
```
希望以上回答能够帮助到你!
(1) 创建ArrayList类对象fruitList,向其中放入代表5种水果的 名称。 (2) 输出每种水果的名称。 [banana, apple, orange, peach, pineapple]
好的,您的要求已经记录下来了,下面是您的答案:
```java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// 创建ArrayList类对象fruitList,向其中放入代表5种水果的名称
ArrayList<String> fruitList = new ArrayList<String>();
fruitList.add("banana");
fruitList.add("apple");
fruitList.add("orange");
fruitList.add("peach");
fruitList.add("pineapple");
// 输出每种水果的名称
for (String fruit : fruitList) {
System.out.print(fruit + " ");
}
}
}
```
输出结果为:
```
banana apple orange peach pineapple
```