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

发布于:2024-05-16 ⋅ 阅读:(38) ⋅ 点赞:(0)

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

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

2. 

具体来说,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]

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

先看不高效的方式:

# 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
# 使用列表来收集字符串片段,然后使用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"字符串的拼接结果  
    }  
}