数据结构及算法——数组和字符串一些记录

  1. 在Python中,任何非零整数值(包括1)在布尔上下文中都被视为True

也就是if 非0: 该条件就为True,if 0该条件就为False

具体来说,lst[start:stop:step] 是Python中列表切片的基本语法。在这个语法中:

  • start 是开始索引(包含),默认为0。
  • stop 是结束索引(不包含),默认为列表长度。
  • step 是步长,默认为1。当步长为负数时,切片会反向进行。

lst[::-1] 这个例子中:

  • 没有指定 start,所以默认为0。

  • 没有指定 stop,所以默认为列表的长度。

  • step 被设置为 -1,表示反向切片。

    lst = [1, 2, 3, 4, 5, 6]
    reversed_lst = lst[::-1]
    print(reversed_lst) # 输出: [6, 5, 4, 3, 2, 1]

  1. 字符串高效的拼接方式

先看不高效的方式:

python 复制代码
# python
def joint_str(str):
    s=''
    for i in range(10000):
        s += '_Hello_'
    print(s)

# java,每次拼接都会创建一个String对象,当 n 的值很大时(比如 n = 10000),这段代码会消耗大量的时间和内存,并可能导致性能问题,甚至 OutOfMemoryError。
public class Main {
    public static void main(String[] args) {
        String s = "";
        int n = 10000;
        for (int i = 0; i < n; i++) {
            s += "hello";
        }
    }

高效方式:

python 复制代码
# python
# 使用列表来收集字符串片段,然后使用join()来拼接它们  
strings = []  
n = 10000  
for i in range(n):  
    strings.append("hello")  
  
# 使用join()方法来拼接字符串  
s = ''.join(strings)  
  
# 现在s包含了n个"hello"字符串的拼接结果  
print(s)


# java
public class Main {  
    public static void main(String[] args) {  
        StringBuilder sb = new StringBuilder();  
        int n = 10000;  
        for (int i = 0; i < n; i++) {  
            sb.append("hello");  
        }  
        String s = sb.toString(); // 当你需要字符串时才转换为String  
        // 现在你可以使用s了,它包含了n个"hello"字符串的拼接结果  
    }  
}
相关推荐
冷雨夜中漫步3 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴3 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
JH30734 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
喵手5 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
Coder_Boy_5 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy5 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
invicinble5 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟6 小时前
使用ASM和agent监控属性变化
java