通讯录排序
时间: 2023-07-01 14:06:51 浏览: 130
通讯录排序可以按照姓名、拼音、电话号码等多种方式进行。
以下是按照姓名首字母排序的示例代码:
```python
contacts = ['张三', '李四', '王五', '赵六', '钱七']
sorted_contacts = sorted(contacts, key=lambda x: x[0])
print(sorted_contacts)
```
输出结果:
```
['李四', '钱七', '张三', '赵六', '王五']
```
其中,`sorted()` 函数接受一个可迭代对象和一个 `key` 参数,`key` 参数指定排序时使用的函数,这里使用 `lambda` 表达式指定以姓名首字母作为排序依据。
相关问题
pta通讯录排序python
以下是一个简单的 Python 代码示例,可以对 PTA 通讯录进行排序:
```python
contacts = [('张三', '1234567'), ('李四', '9876543'), ('王五', '2468101')]
# 按照姓名进行排序
sorted_contacts = sorted(contacts, key=lambda x: x[0])
print(sorted_contacts)
# 输出:[('李四', '9876543'), ('王五', '2468101'), ('张三', '1234567')]
# 按照电话号码进行排序
sorted_contacts = sorted(contacts, key=lambda x: x[1])
print(sorted_contacts)
# 输出:[('王五', '2468101'), ('张三', '1234567'), ('李四', '9876543')]
```
在这个示例中,我们首先定义了一个包含联系人姓名和电话号码的元组列表。然后我们使用 Python 的 `sorted()` 函数进行排序,通过 `key` 参数指定按照姓名或电话号码进行排序。最后,我们打印排序后的结果。
你可以根据自己的需求修改代码,实现你所需要的排序方式。
c语言结构体-通讯录排序
以下是C语言结构体通讯录按名字首字母排序的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_LEN 20
#define MAX_REMARK_LEN 50
#define MAX_CONTACT_NUM 100
struct Contact {
struct ConInfo {
char name[MAX_NAME_LEN];
char sex;
char phone[MAX_PHONE_LEN];
char remark[MAX_REMARK_LEN];
} data[MAX_CONTACT_NUM];
int sz;
};
int cmp_name(const void* s1, const void* s2) {
return strcmp(((struct ConInfo*)s1)->name, ((struct ConInfo*)s2)->name);
}
void Sort(const struct Contact* pc) {
qsort(pc->data, pc->sz, sizeof(struct ConInfo), cmp_name);
Show(pc);
}
void Show(const struct Contact* pc) {
printf("姓名\t性别\t电话\t\t备注\n");
for (int i = 0; i < pc->sz; ++i) {
printf("%s\t%c\t%s\t%s\n", pc->data[i].name, pc->data[i].sex, pc->data[i].phone, pc->data[i].remark);
}
}
int main() {
struct Contact con = { 0 };
con.sz = 3;
strcpy(con.data[0].name, "Tom");
con.data[0].sex = 'M';
strcpy(con.data[0].phone, "123456789");
strcpy(con.data[0].remark, "good boy");
strcpy(con.data[1].name, "Jerry");
con.data[1].sex = 'F';
strcpy(con.data[1].phone, "987654321");
strcpy(con.data[1].remark, "bad girl");
strcpy(con.data[2].name, "Bob");
con.data[2].sex = 'M';
strcpy(con.data[2].phone, "111111111");
strcpy(con.data[2].remark, "handsome boy");
Sort(&con);
return 0;
}
```