python 我可以将字符串添加到压缩列表中吗?

qnyhuwrf  于 2022-12-02  发布在  Python
关注(0)|答案(2)|浏览(142)

我是4类到我的第一个编程类,我被难住了。我想知道我是否能够添加字符串到三个压缩列表?
例如,我需要添加以下格式:
'+'部门名称,(部门编号,产品变量)
其中department_name、department_number、product_variable是压缩在一起的单独列表,我需要在开头添加+,并在两个列表周围添加括号。
这就是我所拥有的:

output = zip(department_name, department_number, product_variable)

for department_name, department_number, product_variable in zip(department_name, department_number, product_variable):

    print (department_name, department_number, product_variable)

有什么想法吗?

rjee0c15

rjee0c151#

You may need string formatting.

department_names = ["n1", "n2", "n3", "n4"]
department_numbers = [1, 2, 3, 4]
product_variables = ["p1", "p2", "p3", "p4"]

for department_name, department_number, product_variable in zip(department_names, department_numbers, product_variables):
    print(f"'+' {department_name}, ({department_number}, {product_variable})")

Output:

'+' n1, (1, p1)
'+' n2, (2, p2)
'+' n3, (3, p3)
'+' n4, (4, p4)
cunj1qz1

cunj1qz12#

l1= [
    {'id': '2', 'name': 'Sou', 'Medicine': 'Paracetamol'},
    {'id': '2', 'name': 'Sou', 'Medicine': 'Supradyn'},
     {'id': '3', 'name': 'Roopa', 'Medicine': 'Revital'},
    {'id': '3','name': 'Roopa', 'Medicine': 'Pain killer'},
    {'id': '4','name': 'Tabu', 'Medicine': 'Vitamin C'}
    
]

def mergeListOfDictionaries1(l1):
    dn = {}
    for d in l1:
        if d['id'] in dn:
           if isinstance(dn[d['id']]['Medicine'],list):
              dn[d['id']]['Medicine'].append(d['Medicine'])
           else:
               dn[d['id']]['Medicine'] = [dn[d['id']]['Medicine'],d['Medicine'] ]
               
        else:
            dn[d['id']] = d
            
    return list(dn.values())                   
           
aa= mergeListOfDictionaries1(l1)
print(aa)

"""
[{'id': '2', 'name': 'Sou', 'Medicine': ['Paracetamol', 'Supradyn']}, 
{'id': '3', 'name': 'Roopa', 'Medicine': ['Revital', 'Pain killer']}, 
{'id': '4', 'name': 'Tabu', 'Medicine': 'Vitamin C'}]

"""

    import itertools, pandas as pd
    
    l1 = ["n1", "n2", "n3", "n4"]
    l2 = [1, 2, 3, 4]
    l3 = ["p1", "p2", "p3", "p4"]
    
    
    nest = [l1,l2,l3]     
    cc = pd.DataFrame(
        (x for x in itertools.zip_longest(*nest))
        )
    print(cc)
"""
Output : 
   0  1  2
0  A  1  P
1  B  2  Q
2  C  3  R
"""


 for l1,l2,l3 in zip(l1,l2,l3):
        print(l1 , '+',l2 , '+',  l3)
"""
Print all and put a plus sign in between so that the output becomes
A + 1 + P
B + 2 + Q
C + 3 + R
D + 4 + S
"""

现在如果我们想压缩和打印不同列表中的替代词。输出:[(“A”,1,“P”),(“B”,2,“Q”),(“C”,3,“R”),(“D”,4,“S”)]然后,

l1 = ["A", "B", "C", "D"]
    l2 = [1, 2, 3, 4]
    l3 = ["P", "Q", "R", "S"]
    
    
        def zipAlternate(list1,*rest,fillvalue=None):
            rest = [iter(r) for r in rest]
            for x in list1:
                res = yield x, *[next(r,fillvalue) for r in rest]
            return res    
        zz = zipAlternate(l1,l2,l3)
        zzl = list(zz)
        print(zzl) 
"""
Output :
[('A', 1, 'P'), ('B', 2, 'Q'), ('C', 3, 'R'), ('D', 4, 'S')]

现在,如果给定了几个字符串。l1 = 'ABCDE',l2 = '12',l3 = 'PQXYZ',我们希望输出为' A1PB2QC '。

l1 = 'ABCDE'
l2 = '12'
l3 = 'PQXYZ'
def zipAlternateString(*allString):
    rest = [iter(r) for r in allString]
    str= ''
    while True:
          for r in rest:
              try : 
                   str += next(r)
              except StopIteration:
                     return str      
    return str    
        
aa = zipAlternateString(l1,l2,l3)
print(aa)    
"""
 Output :
 A1PB2QC
"""


d1 = {'A': 'a', 'B': 'b'}
d2 = {'A': 'c', 'B': 'd'}
d3 = {'A': 'e', 'B': 'f'}

aa = {
    
    k : [d1.get(k),d2.get(k),d3.get(k)] for k in d1.keys() | d2.keys() | d3.keys()  
    
    }

print(aa)

"""
{'A': ['a', 'c', 'e'], 'B': ['b', 'd', 'f']}

"""

相关问题