用int连接字符串

时间:2019-06-23 10:10:11

标签: go

我有以下代码,需要获取int值并将其添加到带有字符串后缀的字符串中。例如

一开始我就明白了

"fds data "

if语句之后,它应该这样

"fds data 10 M"

这是代码:

ltrCfg := "fds data "
if len(cfg.ltrSharedDicts) > 0 {
    ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
    ltrCfg += "M"
} else {
    ltrCfg += "10M"
}
out = append(out, ltrCfg)

ltrCert := “fds data "
if len(cfg.ltrSharedDicts) > 0 {
    ltrCert += strconv.Itoa(cfg.ltrSharedDicts["d_data"])
    ltrCert += "M"
} else {
    ltrCert += “20M"
}
out = append(out, ltrCert)

代码正在运行,但我想知道if语句的第一个分支

if len(cfg.ltrSharedDicts) > 0 {
    ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
    ltrCfg += "M"

是否有更好的方法来实现?

1 个答案:

答案 0 :(得分:1)

出于可读性考虑,我会写:

from iteration_utilities import all_distinct
from itertools import combinations
from simple_benchmark import BenchmarkBuilder

# First benchmark
b1 = BenchmarkBuilder()

@b1.add_function()
def all_distinct_set(values):
    return len(set(values)) == len(values)

@b1.add_function()
def all_distinct_set_sc(values):
    seen = set()
    seen_add = seen.add
    last_count = 0
    for item in values:
        seen_add(item)
        new_count = len(seen)
        if new_count == last_count:
            return False
        last_count = new_count
    return True

@b1.add_function()
def all_distinct_list(values):
    seen = []
    for item in values:
        if item in seen:
            return False
        seen.append(item)
    return True

b1.add_function(alias='all_distinct_iu')(all_distinct)

@b1.add_function()
def all_distinct_combinations(values):
    return all(x != y for x, y in combinations(values, 2))

@b1.add_arguments('number of hashable inputs')
def argument_provider():
    for exp in range(1, 12):
        size = 2**exp
        yield size, range(size)

r1 = b1.run()
r1.plot()

# Second benchmark

b2 = BenchmarkBuilder()
b2.add_function(alias='all_distinct_iu')(all_distinct)
b2.add_functions([all_distinct_combinations, all_distinct_list])

@b2.add_arguments('number of unhashable inputs')
def argument_provider():
    for exp in range(1, 12):
        size = 2**exp
        yield size, [[i] for i in range(size)]

r2 = b2.run()
r2.plot()

# Third benchmark
b3 = BenchmarkBuilder()
b3.add_function(alias='all_distinct_iu')(all_distinct)
b3.add_functions([all_distinct_set, all_distinct_set_sc, all_distinct_combinations, all_distinct_list])

@b3.add_arguments('number of hashable inputs')
def argument_provider():
    for exp in range(1, 12):
        size = 2**exp
        yield size, [0, *range(size)]

r3 = b3.run()
r3.plot()

# Fourth benchmark
b4 = BenchmarkBuilder()
b4.add_function(alias='all_distinct_iu')(all_distinct)
b4.add_functions([all_distinct_combinations, all_distinct_list])

@b4.add_arguments('number of hashable inputs')
def argument_provider():
    for exp in range(1, 12):
        size = 2**exp
        yield size, [[0], *[[i] for i in range(size)]]

r4 = b4.run()
r4.plot()
相关问题