代码之家  ›  专栏  ›  技术社区  ›  abc

Python仅将值获取到1到255之间的变量

  •  1
  • abc  · 技术社区  · 8 年前
    data = """
        abcd1   1
        abcd2   2
        abcd3   3
        abcd4   4
        abcd5   5
        abcd6   6
        abcd7   7
        abcd8   8
        abcd9   9
        .
        .
        .
        abcd256 1
        abcd257 2
        abcd258 3
        abcd259 4
        abcd260 5
        abcd261 6
        abcd262 7
        abcd263 8
        abcd264 9
        """
    
    if abcd1, then  Get  value 1,
    if abcd2, then  Get  value 2,...so on
    
    if abcd256, then  Get  value 1,
    if abcd257, then  Get  value 2,
    

    条件值必须介于1到255之间

    数据变量中已存在检查字符串。我使用了以下代码:

    check = set()
    for line in data.split("\n"):
        if len(line.split()) > 1:
            line = line.strip()
            check.add(line.split()[0])
    
    if not "abcd264" in check:
                print "Not exist":
                value = 9#Help required to get value here 
    
    else:
        print "Its already exist. Program exit"
        sys.exit()
    

    建议在其他帖子中使用熊猫,但我需要在不使用熊猫的情况下实施

    2 回复  |  直到 8 年前
        1
  •  2
  •   Vasilis G.    8 年前

    如果您希望使用纯Python进行此操作,可以尝试以下方式:

    data = """
        abcd1   1
        abcd2   2
        abcd3   3
        abcd4   4
        abcd5   5
        abcd6   6
        abcd7   7
        abcd8   8
        abcd9   9
        abcd256 1
        abcd257 2
        abcd258 3
        abcd259 4
        abcd260 5
        abcd261 6
        abcd262 7
        abcd263 8
        abcd264 9
        """
    
    data = data.replace("    ","").replace("   "," ").split("\n")[1:-1]
    for d in data:
        number = int(d.split()[0][4:])
        print("For number %d the result is: %d" % (number,number % 255))
    

    输出:

    For number 1 the result is: 1
    For number 2 the result is: 2
    For number 3 the result is: 3
    For number 4 the result is: 4
    For number 5 the result is: 5
    For number 6 the result is: 6
    For number 7 the result is: 7
    For number 8 the result is: 8
    For number 9 the result is: 9
    For number 256 the result is: 1
    For number 257 the result is: 2
    For number 258 the result is: 3
    For number 259 the result is: 4
    For number 260 the result is: 5
    For number 261 the result is: 6
    For number 262 the result is: 7
    For number 263 the result is: 8
    For number 264 the result is: 9
    
        2
  •  0
  •   jpp    8 年前

    最好通过以下库对操作进行矢量化: pandas 。以下是一个示例:

    from io import StringIO
    import pandas as pd
    
    mystr = """abcd1   1
    abcd2   2
    abcd3   3
    abcd4   4
    abcd5   5
    abcd6   6
    abcd7   7
    abcd8   8
    abcd9   9
    """
    
    df = pd.read_csv(StringIO(mystr), delim_whitespace=True, header=None)
    df['idx'] = df[0].str[4:].astype(int)
    
    res = set(df.loc[df['idx'] <= 5, 1])
    
    # {1, 2, 3, 4, 5}