如何在现有的python中更新string

2024-04-24 13:42:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下命令输出:

data = """
abcd11  11  
abcd12  12  
abcd13  13
abcd21  14
abcd22  15
abcd23  16
abcd101  17
abcd102  18
abcd103  19

... so on
abcd501  1
abcd502  2

"""

条件1数字(根据数据为字符串)范围必须介于1到255之间,即不超过255

代码:

#Check abcd401, abcd402, abcd403   

check = set()
for line in data.split("\n"):
    if len(line.split()) > 1:
        line = line.strip()
        check.add(line.split()[0])

if not "abcd401" in check and not "abcd402" in check and not "abcd402" in check:
            print "Not exist"
else:
    print "Its already exist. Program exit"
    sys.exit()

现在需要给abcd401,abcd402,abcd403赋值

介于1到255之间的数字。你知道吗

我总是可以分配abcd401=1,abcd402=2,abcd403=3,但我需要填写1-255,然后开始1-255,依此类推请帮助。你知道吗


Tags: andindataifchecklineexitnot
1条回答
网友
1楼 · 发布于 2024-04-24 13:42:29
  • 如果数据中不存在行(data),我试图解决添加行的问题 是多行字符串输入内容)。你知道吗
  • 这可以通过熊猫来实现 用简单的方法,如果你用熊猫,解决方案也会变大。你知道吗
  • 是的 不是把重点放在随机分配给每一行的数字上,我只是 循环从1到255,一旦达到idx,我从1开始 再一次。:)
  • 这部分你可以照顾。。。你知道吗

我的快速解决方案是:

import cStringIO as io
import pandas as pd
from itertools import cycle

text_data = """abcd11  11  
abcd12  12  
abcd13  13
abcd21  14
abcd22  15
abcd23  16
abcd101  17
abcd102  18
abcd103  19
abcd501  1
abcd502  2"""


def get_next_id():
    cyc = cycle(range(1,256))
    for i in cyc:
        yield i
next_id = get_next_id()


def load_data():
    content = io.StringIO(text_data)
    df = pd.read_csv(content, header=None, sep="\s+", names=["txt", "num"])
    print "Content is loaded to pandas dataframe\n", df
    return df


def add_line_to_df(txt, df):
    idx = next_id.next()
    df2 = pd.DataFrame([[txt, idx]], columns=["txt", "num"])
    df.loc[len(df.index)] = df2.iloc[0]
    #print df #res_df
    return df # res_df


def insert_valid_line(line, df):
    if line in pd.Series(df["txt"]).values:
        print "{}: already existed.".format(line)
    else:
        print "{}: adding to existing df.".format(line)
        add_line_to_df(line, df)


def main():
    df = load_data()
    new_texts = ["abcd501", "abcd502", "abcd402", "abcd403"]

    for txt in new_texts:
        print "-" * 20
        insert_valid_line(txt, df)

    print "-" * 20
    print df
    #In this place df is holding all the data

if __name__ == '__main__':
    main()

输出如下所示…:

Content is loaded to pandas dataframe
        txt  num
0    abcd11   11
1    abcd12   12
2    abcd13   13
3    abcd21   14
4    abcd22   15
5    abcd23   16
6   abcd101   17
7   abcd102   18
8   abcd103   19
9   abcd501    1
10  abcd502    2
          
abcd501: already existed.
          
abcd502: already existed.
          
abcd402: adding to existing df.
          
abcd403: adding to existing df.
          
        txt  num
0    abcd11   11
1    abcd12   12
2    abcd13   13
3    abcd21   14
4    abcd22   15
5    abcd23   16
6   abcd101   17
7   abcd102   18
8   abcd103   19
9   abcd501    1
10  abcd502    2
11  abcd402    1
12  abcd403    2

相关问题 更多 >