小编ABH*_* EA的帖子

在c中使用const关键字

我一直在查看源代码,我遇到了这段代码

    static char const *const delimit_method_string[] =
    {
        "none", "prepend", "separate", NULL
    };
Run Code Online (Sandbox Code Playgroud)

我以为我知道Cconst语言中关键字的含义,但是看到这个语法后我很困惑,因为我无法解码语法的含义,所以我想知道这样使用的含义我在网上搜索了一些问题就像 stackoverflow 中的这样,const

  1. C/C++签名中两个const的含义
  2. 双常量声明

但我仍然不明白该代码片段中语法的含义是什么,可能是因为我对C的基础知识不够好,但我真的很想改进它。

所以我写了一些代码来了解该语法是如何工作的,这就是我尝试过的:

    #include <stdio.h>
    
    int main()
    {
        char a = 'A';
        char b = 'B';
        char const * const ptr = &a;

        ptr = &b;

        printf("a is %c\n", *ptr);
        printf("a is %c", a);
    
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出,这在某种程度上是我所期望的。

$ gcc test.c
test.c: In function 'main':
test.c:9:13: error: assignment of read-only variable 'ptr'
    9 |         ptr = &b;
      |  

                    ^ …
Run Code Online (Sandbox Code Playgroud)

c syntax pointers constants declaration

6
推荐指数
1
解决办法
216
查看次数

无法获取更改后的全局变量

t.py

value = 0

def change_value():
    global value
    value = 10
Run Code Online (Sandbox Code Playgroud)

间谍

import t
from t import value

t.change_value()

print(f'test1: {t.value}')
print (f'test2: {value}')
Run Code Online (Sandbox Code Playgroud)

输出

测试1:10

测试2:0

为什么它不返回 test2 中更改后的值?

python

4
推荐指数
1
解决办法
111
查看次数

将大文件分割成块

我有一个包含 7946479 条记录的文件,我想逐行读取该文件并插入到数据库(sqlite)中。我的第一种方法是打开文件逐行读取记录并同时插入数据库,因为它处理大量数据,需要很长时间。我想改变这种幼稚的方法,所以当我在互联网上搜索时我看到了这个 [python-csv-to-sqlite][1] ,他们在 csv 文件中有数据,但我的文件是dat格式,但我喜欢这个问题的答案,所以现在我尝试这样做在解决方案中。 /sf/ask/415968171/

他们使用的方法就像首先将整个文件分成块,然后执行数据库事务,而不是一次写入每条记录。

所以我开始编写一个代码来将我的文件分割成块这是我的代码,

file = r'files/jan.dat'
test_file = r'random_test.txt'


def chunks(file_obj, size=10000):
counter = 0
file_chunks = []
temp_chunks = []

for line in file_obj:
    if line == '\n':
        continue
    if counter != size:
        temp_chunks.append(line)
        counter += 1
    else:
        file_chunks.append(temp_chunks)
        temp_chunks = []
        counter = 0
file_obj.close()
if len(temp_chunks) != 0:
    file_chunks.append(temp_chunks)

yield file_chunks

if __name__ == '__main__':
    split_files = chunks(open(test_file))
    for chunk in split_files:
        print(len(chunk))
Run Code Online (Sandbox Code Playgroud)

输出是 795,但我想要的是将整个文件分割成大小为 10000 的块

我不知道这里出了什么问题,我无法在这里共享我的整个文件,因此为了测试可以使用此代码生成一个包含 …

python yield

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

c ×1

constants ×1

declaration ×1

pointers ×1

syntax ×1

yield ×1