如何从元组列表中添加值

时间:2019-07-23 07:23:25

标签: python list tuples add

我正在从日志文件中提取并使用以下代码进行打印

    public List<SelectListItem> LanguagePreference { get; set; } = new List<SelectListItem>
    {
       new SelectListItem { Value = "NA", Text = "-Select-" },
       new SelectListItem { Value = "en-US", Text = "English (United States)"  },
       new SelectListItem { Value = "en-IN", Text = "English (India)"  },
       new SelectListItem { Value = "ta-IN", Text = "Tamil (India)"  },
       new SelectListItem { Value = "hi-IN", Text = "Hindi (India)"  },
       new SelectListItem { Value = "te-IN", Text = "Telugu (India)"  }
    };

如何添加到输出中

输出

for line in data:
    g = re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line)
    print (g)

[('1.1.1.1', 'PUT')]
[('2.2.2.2', 'GET')]
[('1.1.1.1', 'PUT')]
[('2.2.2.2', 'POST')]

5 个答案:

答案 0 :(得分:2)

我会去找柜台。

from collections import Counter
results = []
for line in data:
    g = re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line)
    results.append(g[0])
ip_list = set(result[0] for result in results)
for ip in ip_list:
    print(ip, Counter(result[1] for result in results if result[0] == ip ))

答案 1 :(得分:1)

您可以使用字典来计数:

# initialize the count dict
count_dict= dict()
for line in data:
    g = re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line)
    for tup in g:
        # get the counts for tuple tup if we don't have it yet
        # use 0 (second argument to .get)
        num= count_dict.get(tup, 0)
        # increase the count and write it back
        count_dict[tup]= num+1
# now iterate over the key (tuple) - value (counts)-pairs
# and print the result
for tup, count in count_dict.items():
    print(tup, count)

好吧,我必须承认这并不能提供确切的输出,但是您可以通过类似的方式进行操作:

out_dict= dict()
for (comma_string, request_type), count in count_dict.items():
    out_str= out_dict.get(comma_string, '')
    sep='' if out_str == '' else ', '
    out_str= f'{out_str}{sep}{request_type} = {count}'
    out_dict[comma_string]= out_str

for tup, out_str in out_dict.items():
    print(tup, out_str)

根据输出的数据:

1.1.1.1 PUT = 2
2.2.2.2 GET = 1, POST = 1

答案 2 :(得分:1)

您可以使用collection.defaultdict

例如:

from collections import defaultdict

result = defaultdict(list)
for line in data:
    for ip, method in re.findall(r'([\d.]+).*?(GET|POST|PUT|DELETE)', line):
        result[ip].append(method)

for k, v in result.items():
    temp = ""
    for i in set(v):
        temp += " {} = {}".format(i, v.count(i))
    print("{}{}".format(k, temp))

答案 3 :(得分:1)

from collections import Counter  
x = [[('1.1.1.1', 'PUT')],[('2.2.2.2', 'GET')],[('1.1.1.1', 'PUT')],[('2.2.2.2', 'POST')]]
# step 1: convert x into a dict.
m = {}
for i in x:
    a, b = i[0]
    if a not in m.keys():
        m[a] = [b] 
    else: 
        x = m[a] 
        x.append(b)
        m[a] = x    
print('new dict is {}'.format(m))

# step 2 count frequency
m_values = list(m.values())
yy = []
for i in m_values:
    x = []
    k = list(Counter(i).keys())
    v = list(Counter(i).values())
    for i in range(len(k)):       
        x.append(k[i] + '=' + str(v[i]))
    yy.append(x)

# step 3, update the value of the dict
m_keys =  list(m.keys())
n = len(m_keys)
for i in range(n):
    m[m_keys[i]] = yy[i]

print("final dict is{}".format(m))

输出为

new dict is {'1.1.1.1': ['PUT', 'PUT'], '2.2.2.2': ['GET', 'POST']}
final dict is{'1.1.1.1': ['PUT=2'], '2.2.2.2': ['GET=1', 'POST=1']}

答案 4 :(得分:1)

没有依赖项,并且以非常基本的方式使用字典进行计数。鉴于fetch('/lom').then((res)=>{ console.log(res); }); //GET Request

data_set

初始化变量(通常只有几个动词),然后遍历数据:

data_set = [[('1.1.1.1', 'PUT')],
            [('2.2.2.2', 'GET')],
            [('2.2.2.2', 'POST')],
            [('1.1.1.1', 'PUT')]]

需要格式化输出以更好地满足您的需求。