相关疑难解决方法(0)

迭代字符串的行

我有一个像这样定义的多行字符串:

foo = """
this is 
a multi-line string.
"""
Run Code Online (Sandbox Code Playgroud)

这个字符串我们用作我正在编写的解析器的测试输入.解析器函数接收一个file-object作为输入并迭代它.它也next()直接调用方法来跳过行,所以我真的需要一个迭代器作为输入,而不是迭代.我需要一个迭代器,迭代遍历该字符串的各个行,就像file一个文本文件的行一样.我当然可以这样做:

lineiterator = iter(foo.splitlines())
Run Code Online (Sandbox Code Playgroud)

有更直接的方法吗?在这种情况下,字符串必须遍历一次以进行拆分,然后再由解析器遍历.在我的测试用例中没关系,因为那里的字符串很短,我只是出于好奇而问.Python为这些东西提供了许多有用且高效的内置插件,但我找不到任何适合这种需求的东西.

python string iterator

110
推荐指数
3
解决办法
11万
查看次数

如何使python解释器正确处理字符串操作中的非ASCII字符?

我有一个看起来像这样的字符串:

6 918 417 712
Run Code Online (Sandbox Code Playgroud)

修剪这个字符串的明确方法(据我理解Python)只是说字符串在一个名为的变量中s,我们得到:

s.replace('Â ', '')
Run Code Online (Sandbox Code Playgroud)

这应该够了吧.但当然它抱怨'\xc2'文件blabla.py 中的非ASCII字符未编码.

我永远不会理解如何在不同的编码之间切换.

这是代码,它实际上与上面相同,但现在它在上下文中.该文件在记事本中保存为UTF-8,并具有以下标头:

#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)

代码:

f = urllib.urlopen(url)

soup = BeautifulSoup(f)

s = soup.find('div', {'id':'main_count'})

#making a print 's' here goes well. it shows 6Â 918Â 417Â 712

s.replace('Â ','')

save_main_count(s)
Run Code Online (Sandbox Code Playgroud)

它不过是s.replace......

python unicode

100
推荐指数
6
解决办法
17万
查看次数

Python字符串'join'比'+'更快(?),但这里有什么问题?

我在早期的帖子中询问了最有效的大规模动态字符串连接方法,我建议使用join方法,这是最好,最简单,最快速的方法(就像大家所说的那样).但是当我玩字符串连接时,我发现了一些奇怪的(?)结果.我确信事情正在发生,但我不能完全理解.这是我做的:

我定义了这些功能:

import timeit
def x():
    s=[]
    for i in range(100):
        # Other codes here...
        s.append("abcdefg"[i%7])
    return ''.join(s)

def y():
    s=''
    for i in range(100):
        # Other codes here...
        s+="abcdefg"[i%7]
    return s

def z():
    s=''
    for i in range(100):
        # Other codes here...
        s=s+"abcdefg"[i%7]
    return s

def p():
    s=[]
    for i in range(100):
        # Other codes here...
        s+="abcdefg"[i%7]
    return ''.join(s)

def q():
    s=[]
    for i in range(100):
        # Other codes here...
        s = s + ["abcdefg"[i%7]]
    return ''.join(s) …
Run Code Online (Sandbox Code Playgroud)

python string performance

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

Python 3.11 的优化比 3.10 差?

我在 Windows 10 上使用 Python 3.10.7 和 3.11.0 运行这个简单的循环。

import time
a = 'a'

start = time.time()
for _ in range(1000000):
    a += 'a'
end = time.time()

print(a[:5], (end-start) * 1000)
Run Code Online (Sandbox Code Playgroud)

旧版本执行时间为 187ms,Python 3.11 需要大约 17000ms。3.10 是否意识到只需要 的前 5 个字符a,而 3.11 执行整个循环?我在 godbolt 上证实了这种性能差异。

python optimization performance python-3.10 python-3.11

22
推荐指数
1
解决办法
2279
查看次数

连接列表的元素

我有一个列表,就像l=['a', 'b', 'c'] 我想要一个像'abc'这样的字符串.所以实际上结果是l[0]+l[1]+l[2],也可以写成

s = ''
for i in l:
    s += i
Run Code Online (Sandbox Code Playgroud)

有没有办法更优雅地做到这一点?

python string concatenation

8
推荐指数
1
解决办法
9313
查看次数

为什么'new_file + = line + string'比'new_file = new_file + line + string'快得多?

当我们使用时,我们的代码需要10分钟来虹吸68,000条记录:

new_file = new_file + line + string
Run Code Online (Sandbox Code Playgroud)

但是,当我们执行以下操作时,只需1秒钟:

new_file += line + string
Run Code Online (Sandbox Code Playgroud)

这是代码:

for line in content:
import time
import cmdbre

fname = "STAGE050.csv"
regions = cmdbre.regions
start_time = time.time()
with open(fname) as f:
        content = f.readlines()
        new_file_content = ""
        new_file = open("CMDB_STAGE060.csv", "w")
        row_region = ""
        i = 0
        for line in content:
                if (i==0):
                        new_file_content = line.strip() + "~region" + "\n"
                else:
                        country = line.split("~")[13]
                        try:
                                row_region = regions[country]
                        except KeyError:
                                row_region = "Undetermined"
                        new_file_content += …
Run Code Online (Sandbox Code Playgroud)

python string cpython string-concatenation python-internals

8
推荐指数
2
解决办法
1108
查看次数

Python中的字符串连接

你能描述两种字符串连接方式之间的区别:简单的__add__运算符和%s模式吗?我在这个问题上进行了一些调查,发现%s(没有使用括号的形式)更快一点.

还出现了另一个问题:为什么结果'hell%s' % 'o'指的是另一个记忆区域'hell%s' % ('o',)

有一些代码示例:

l = ['hello', 'hell' + 'o', 'hell%s' % 'o', 'hell%s' % ('o',)]
print [id(s) for s in l]
Run Code Online (Sandbox Code Playgroud)

结果:

[34375618400, 34375618400, 34375618400, 34375626256]
Run Code Online (Sandbox Code Playgroud)

PS我知道字符串实习:)

python compilation internals object-identity

3
推荐指数
1
解决办法
327
查看次数

为什么连接字符串比连接它们更快?

据我所知,".join(iterable_of_strings)是连接字符串的首选方法,因为它允许优化,避免必须将不可变对象重写到内存的次数超过必要时间.

在表达式中添加字符串可靠地运行得比为它进行适度大量操作而加入它们更快.

我在加入时获得了大约2.9-3.2秒的时间,并且在我的笔记本电脑上使用Python 3.3添加了运行此代码的2.3-2.7.谷歌搜索这个我找不到一个好的答案.有人可以解释可能发生的事情或指导我找到一个好的资源吗?

import uuid
import time

class mock:
    def __init__(self):
        self.name = "foo"
        self.address = "address"
        self.age = "age"
        self.primarykey = uuid.uuid4()

data_list = [mock() for x in range(2000000)]

def added():
    my_dict_list = {}
    t = time.time()
    new_dict = { item.primarykey: item.name + item.address + item.age for item in data_list }
    print(time.time() - t)

def joined():
    my_dict_list = {}
    t = time.time()
    new_dict = { item.primarykey: ''.join([item.name, item.address, item.age]) for item in data_list }
    print(time.time() - t)

joined() …
Run Code Online (Sandbox Code Playgroud)

python memory string loops python-3.3

3
推荐指数
1
解决办法
336
查看次数

Python Pandas:.apply 需要永远?

我有一个通过解析 1.4G 大小的 CSV 创建的 DataFrame 'clicks'。我正在尝试使用 apply 函数创建一个新列“购买”。

clicks['bought'] = clicks['session'].apply(getBoughtItemIDs)
Run Code Online (Sandbox Code Playgroud)

在 getBoughtItemIDs 中,我正在检查“buys”数据框是否具有我想要的值,如果是,则返回连接它们的字符串。getBoughtItemIDs 中的第一行永远占用。有什么方法可以让它更快?

def getBoughtItemIDs(val):
  boughtSessions = buys[buys['session'] == val].values
  output = ''
  for row in boughtSessions:
    output += str(row[1]) + ","
  return output
Run Code Online (Sandbox Code Playgroud)

python machine-learning dataframe pandas

3
推荐指数
1
解决办法
3176
查看次数

有点像连接但不完全

for seqA in poolA:
    print seqA + ":",
    for i in seqA:
        print complements[i],
    print
Run Code Online (Sandbox Code Playgroud)

complements是一个dict,poolA是一个list.

当我print complements[i]中间有空格时,如何删除这些空格?

python concatenation

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

如何使用Python减少字符串中的重复字符

有没有办法将重复的字符减少到特定的数字,例如,如果我们有这个字符串.

"I liiiiked it, thaaaaaaank you"

预期产量: "I liiiiked it thaaaank you"

因此,如果重复的字符超过4,例如,它应该减少到只有4个字符,如果它小于或等于4,那么该字应该保持不变.

python string duplicate-removal

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

Python - 创建一个在字母之间添加" - "的函数

我正在尝试创建一个函数f(x),它会"-"在每个字母之间添加一个:

例如:

f("James")
Run Code Online (Sandbox Code Playgroud)

应输出为:

J-a-m-e-s-
Run Code Online (Sandbox Code Playgroud)

如果您可以使用简单的python函数,我会喜欢它,因为我是编程新手.提前致谢.另外,请使用"for"功能,因为这是我正在努力学习的内容.

编辑:

是的,我确实想要"-"之后的"s".

python

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